繁体   English   中英

在ComponentDidMount中分配值,而不是React中的构造函数

[英]Assignment of value in ComponentDidMount instead of constructor function in React

以下是我的代码(工作正常),其中我可以根据文本框中提供的输入对列表进行排序。 constructor方法中,我这样声明了我的状态-

this.state = {
      data: ["Adventure", "Romance", "Comedy", "Drama"],
      tableData: []
    };

componentDidMount方法中,我在tableData分配data键状态。

  componentDidMount() {
    this.setState({
      tableData: this.state.data
    });
  }

我的问题是-这样做是否正确,因为我自己对此代码质量tableData: this.state.data初始化为[] ,然后在componentDidMount方法中设置tableData: this.state.data )。 让我知道是否可以改善这一点,如果我从API fetch数据(这是在应用中进行初始化和使用的最佳位置)的数据,将会发生什么变化。

工作代码示例-https://codesandbox.io/s/k9j86ylo4o

代码-

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: ["Adventure", "Romance", "Comedy", "Drama"]
    };
    this.handleChange = this.handleChange.bind(this);
  }

  refineDataList(inputValue) {
    const listData = this.state.data;
    const result = listData.filter(item =>
      item.toLowerCase().match(inputValue.toLowerCase())
    );
    this.setState({
      data: result
    });
  }

  handleChange(e) {
    const inputValue = e && e.target && e.target.value;
    this.refineDataList(inputValue);
  }
  render() {
    return (
      <div className="App">
        <h3>DATA SEARCH</h3>
        <div className="form">
          <input type="text" onChange={this.handleChange} />
        </div>
        <div className="result">
          <ul>
            {this.state.data &&
              this.state.data.map((item, i) => {
                return <li key={i}>{item}</li>;
              })}
          </ul>
        </div>
      </div>
    );
  }
}

您的工作做得很好,但您是对的,有一种更好的方法可以解决,难以维护两个事实点,因此您应该只有一个包含所需单词的数据数组,因此应该过滤值是通过创建一个filter变量进入状态来存储当前要过滤的单词,因此您应该添加类似

// in the constructor function
constructor(props) {
  super(props);
  this.state = {
    data: ["Adventure", "Romance", "Comedy", "Drama"],
    filter: ""
  }
}

// create a filter function
getFilteredResults() {
  const { filter, data } = this.state;
  return data.filter(word => String(word).toLowerCase().match(filter));
}

// and finally into your render function
render() {
  return (
    <div>
      {this.getFilteredResults().map((word) => (
        <div>{word}</div>
      ))}
    </div>
  );
}

显然记得要更新您的handleChange函数,就像这样

handleChange(e) {
  const inputValue = e && e.target && e.target.value;
  this.setState({ filter: inputValue });
  //this.refineDataList(inputValue);
}

这样,您将只维护一个事实点,它将按预期工作。

注意:我们使用String(word).toLowerCase()来确保当前word实际上是一个string ,因此,如果由于某种原因word不是string ,我们可以避免toLowerCase is not function of undefined错误的toLowerCase is not function of undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM