gpt4 book ai didi

javascript - React.js 为什么组件在更改 props 后不会立即重新渲染

转载 作者:行者123 更新时间:2023-11-28 03:57:06 24 4
gpt4 key购买 nike

我有一个名为 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 状态,因此正在加载来自状态的数据的预测组件。没有不必要的细节的预测补偿如下所示:

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的prop被更改,以便表中的标题。但所有表格单元格都保留旧值,直到我单击“检查!” btn 再次(第二次)使用相同的输入值第二次更新它们的值,这正是我在单击一次而不是两次后所做的预期。

最佳答案

将您的代码更改为此。您应该使用新的 Prop 数据重新渲染。

componentWillReceiveProps(nextProps){
if(this.props.forecastData !== nextProps.forecastData){
this.displayInfo(nextProps.forecastData);
}
}

关于javascript - React.js 为什么组件在更改 props 后不会立即重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com