繁体   English   中英

react.js为什么更改道具后组件不会立即重新渲染

[英]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.

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