我一直坚持这样的架构:
基本上,顶级Component 1
定义了作为道具传递给Component 2
的函数和数据,然后又作为道具Component 3
传递给了Component 1
,其中呈现了数据,以及这些函数被调用。
到目前为止,此方法运行良好,但现在的问题是Component 2
引入了对一个异步函数的调用,该函数返回一个promise,当解析后,该函数将更新原始数据,稍后将它们作为prop传递给Component 3
,但是Component 3
永远不会被告知数据已被更新,因此,它永远不会重新渲染也永远不会显示更新的数据。
由于不允许我更改这种失败的体系结构,因此我需要一些有关Component 1
更新原始道具时如何重新渲染True
的建议?
答案 0 :(得分:0)
错误可能是道具从第一部分传递到第三部分的方式,请检查以下基本工作示例:
class Hello extends React.Component {
constructor(props){
super(props);
this.state = {
fromFirst: 0
}
}
componentWillMount(){
// Used just as example of async triggering
setTimeout(() => {
this.setState({fromFirst: 1})
}, 2000)
}
render() {
return (
<div>
Hello {this.props.name}
<SecondComponent fromFirst={this.state.fromFirst} />
</div>
)
}
}
class SecondComponent extends React.Component {
constructor(props){
super(props);
this.state = {
fromSecond: 2
}
}
render() {
return (
<div>
<p> From First: {this.props.fromFirst} </p>
<p> On Second: {this.state.fromSecond}</p>
<ThirdComponent fromFirst={this.props.fromFirst} fromSecond={this.state.fromSecond}/>
</div>)
}
}
class ThirdComponent extends React.Component{
constructor(props){
super(props);
this.state = {
fromThird: 2
}
}
render(){
return (
<div>
<p>Third asks of first {this.props.fromFirst}</p>
</div>
)
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
检查工作JSFiddle
答案 1 :(得分:0)