![](/img/trans.png)
[英]React.js useState function passed as a parameter doesn't rerender its component
[英]react.js why component doesn't rerender immediately after changing props
我得到了名為App的組件,它具有一個按鈕,可通過prop為名為Forecast的組件提供數據
<form onSubmit={this.searchFor}>
<input type="text" placeholder="Enter localization" ref={(input) => { this.textInput = input; }}/>
<button onClick={this.searchFor}>Check!</button>
<button onClick={this.getCoords}>Find me!</button>
</form>
{weatherInfo && <Forecast forecastData={weatherInfo}/> }
經過檢查! 單擊按鈕,將完成api調用並設置了weatherInfo state,因此從該狀態加載了Forecast組件。 沒有不必要的詳細信息的預測補償如下所示:
displayInfo(weatherInfo) {
const {displayItemTo,displayItemFrom} = this.state;
let {displayItems} = this.state;
displayItems = weatherInfo.list.filter((item, idx) => {
return idx < displayItemTo && idx >= displayItemFrom;
}).map((item,idx) =>{
return [
<td>{new Date(item.dt_txt.slice(0,10)).getDay()}</td>,
<td>{item.dt_txt.slice(0,10)}</td>,
<td>{item.dt_txt.slice(11,19)}</td>,
... and few more <td>
});
this.setState({
displayItems:displayItems[0].map((col, i) => displayItems.map(row => row[i]))
});}
基本上displayInfo正在准備數據,稍后將進行映射
這是生命周期方法,我認為這是麻煩制造者
componentDidMount(){
this.displayInfo(this.props.forecastData);
}
componentWillReceiveProps(nextProps){
if(this.props.forecastData !== nextProps){
this.displayInfo(this.props.forecastData);
}
}
以及下面的渲染功能:
render(){
const weatherInfo = this.props.forecastData,
rowNames = ['day','data','hour','temp','humidity','conditions','','windspd','winddir'],
{displayItemTo,displayItemFrom,displayItems} = this.state
console.log(displayItems);
return(
<div className="tableBox">
<div className="back"></div>
<table>
<caption>{weatherInfo.city.name + " , " + weatherInfo.city.country}</caption>
<tbody>
{displayItems.map((item,idx) =>{
return <tr key={idx}><td key={'rowName'+idx}>{rowNames[idx]}</td>{[...item]}</tr>
})}
</tbody>
問題是,當我進入本地化並第一次單擊時,所有內容都呈現完美,但是在安裝組件並單擊“檢查!”時, btn(與其他輸入值val)一次,更改了名為ForecastData的屬性,以便在表中顯示標題。 但是所有表格單元格都保持舊值,直到我點擊“檢查!” 再次btn(第二次)第二次使用相同的輸入值,而不是它們的值正在更新,這正是我兩次單擊一次后所期望的。
將代碼更改為此。 您應該使用新的道具數據重新渲染。
componentWillReceiveProps(nextProps){
if(this.props.forecastData !== nextProps.forecastData){
this.displayInfo(nextProps.forecastData);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.