在React组件中为ES6分配属性

RRP*_*RRP 4 javascript ecmascript-6 reactjs

我是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>
     )
    }

}
Run Code Online (Sandbox Code Playgroud)

如何在全局声明"响应"变量,从ajax调用"obj.responseText"分配数据?

Jim*_*ien 7

看起来你知道自己想要达到什么目标,但对于如何实现目标却有点困惑.

强烈建议您在进一步阅读之前阅读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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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