【问题标题】:Assigning a property with ES6 in a React Component在 React 组件中使用 ES6 分配属性
【发布时间】:2015-10-27 17:09:21
【问题描述】:

我是 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”变量?

【问题讨论】:

  • constructor(){this.response = null;} 在这之后你把你的价值放在search(){ this.response = obj.responseText; } 也许?
  • 你不需要一个全局变量,你只需要一个实例属性。
  • 你能告诉我们你是如何在 ES5 中做到这一点的吗?顺便说一句,ajax 是异步的,所以要考虑到这一点。
  • @Bergi search(){} 是处理 ajax 的函数,它将附加到元素之一上的事件处理程序
  • 你绝对应该先阅读更多关于 React 的内容:facebook.github.io/react/docs/thinking-in-react.html

标签: javascript reactjs ecmascript-6


【解决方案1】:

您似乎知道自己想要实现的目标,但对如何实现有点困惑。

我会强烈建议您在继续之前阅读React documentation

为什么不用全局变量?

如何全局声明response 变量?

简而言之,不要。全局变量是well-documented as being evil。这个组件的一个实例在一个页面中使用全局变量来存储其搜索结果会很好,但想象一下,如果您有两个或更多实例 - 它们都会共享/覆盖彼此的搜索结果。

介绍状态

相反,您想使用 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 替换为看起来几乎相同的事件处理程序。

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2020-06-11
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多