在React组件中分配带有ES6的属性

Assigning a property with ES6 in a React Component

本文关键字:ES6 属性 分配 React 组件      更新时间:2023-09-26

我是ES6的新手,仍在努力掌握新规范的概念,我目前正在React中开发一个组件,在那里我需要进行ajax调用并将此响应存储在对象中。然后使用这个对象来映射必要的元素

我的组件看起来像下面的

export class App extends Component {
    search(){
      //make ajax call
      response = obj.responseText;
    }
    getValues(){}
    render(){
     let result = response.data.map(this.getValues);
     return(
       <div onKeyDown={this.search.bind(this)}>{result}</div>
     )
    }
}

如何全局声明从ajax调用"obj.responseText"分配数据的"response"变量?

你似乎知道自己想要实现什么,但对如何实现有点困惑。

我强烈建议您在进一步阅读React文档之前阅读该文档。

为什么不使用全局变量

如何全局声明response变量?

简而言之,不要。全局变量被充分证明是邪恶的。在一个带有全局变量来存储搜索结果的页面中,该组件的一个实例是可以的,但想象一下,如果你有两个或多个实例,它们都会共享/覆盖彼此的搜索结果。

介绍状态

相反,您希望使用React的组件状态功能来存储搜索结果。

您可以通过在组件的构造函数中设置组件的this.state来设置初始状态(或者在ES5中,在组件上定义getInitialState方法)。

然后,任何时候想要更新组件的状态,都可以调用其this.setState(...)方法,传入一个新的状态对象。这也将触发组件的重新渲染。

示例

下面是一个遵循上述模式的简单实现:

export class App extends Component {
  // Set the initial state of the component in the constructor
  constructor(props) {
    super(props);
    this.state = {};
  }
  // This gets called when your component is mounted
  componentDidMount() {
    // Here we make our AJAX call. I'll leave that up to you
    performMyAjaxMethodDefinedSomewhereElse(result => {
      // We call this method to update `this.state` and trigger re-rendering
      this.setState({ result });
    });
  }
  render() {
    // If we haven't received any results yet, display a message
    if (!this.state.result) {
      return (
        <div>No results!</div>
      );
    }
    // Iterate over the results and show them in a list
    const result = this.state.result.map(text => (<li>{text}</li>));
    // Display the result
    return (
      <ul>{result}</ul>
    );
  }
}

当然,如果您不希望AJAX调用立即启动,您可以使用非常类似的方法,用看起来几乎相同的事件处理程序替换componentDidMount