【发布时间】:2018-09-26 12:24:58
【问题描述】:
情况
我有一个渲染一些子组件的父组件。 子组件应该显示从父组件传递过来的信息。
上下文
多人战舰游戏:
父组件包含一个 10x10 到 10x30 按钮(子组件)的字段。如果按下按钮,则带有按钮位置的信号会发送到 api。 api决定按下的按钮是否需要改变它的颜色。
问题
通过更新父组件的状态,如果子组件是动态创建的,则不会更新子组件道具。
解决方案尝试
不要动态渲染 Childs:
在我的情况下不可能
使用redux
我认为子组件是转储/展示组件,因为它只显示信息。在我的情况下,还有 100-300 个子组件。 Redux and React
使用参考
有 100-300 个子组件...Don’t Overuse Refs
问题
我该怎么办?有没有非反模式的解决方案?
当前代码
class Parent extends React.Component {
constructor(props) {
super(props);
this.state={
foo: 'BAR'
}
this.child=undefined;
}
componentWillMount(){
this.child=<Child foo={this.state.foo}/>
}
componentDidMount(){
var that=this
setTimeout(function(){
that.setState({ //it is just here for demonstration
foo: 'FOO'
})
}, 1000);
}
render() {
return (
<div>
Is: {this.child}
Not Dynamic created: <Child foo={this.state.foo}/>
Actual: <p>{this.state.foo}</p>
</div>
);
}
}
class Child extends React.Component {
render() {
return (
<p>{this.props.foo}</p>
);
}
}
ReactDOM.render(<Parent />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
使用@RaghavGarg 和@Clinton Blackburn 方法编写的代码
class Parent extends React.Component {
constructor(props) {
super(props);
this.state={
foo: 'BAR'
}
this.child=undefined;
}
componentDidMount(){
var that=this
setTimeout(function(){
that.setState({ //it is just here for demonstration
foo: 'FOO'
})
}, 1000);
}
renderChild(){
return <Child foo={this.state.foo} />
}
render() {
const child=this.renderChild()
return (
<div>
Is: {child}
Not Dynamic created: <Child foo={this.state.foo}/>
Actual: <p>{this.state.foo}</p>
</div>
);
}
}
class Child extends React.Component {
render() {
return (
<p>{this.props.foo}</p>
);
}
}
ReactDOM.render(<Parent />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
【问题讨论】:
标签: javascript reactjs redux react-redux