[英]React Native: when should you call function in constructor vs componentDidMount
[英]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.