Javascript 从父级刷新子级状态
我有一个包含一些数据的表,表中的每个元素都是React类组件。看起来是这样的: 我只想为“全部检查”功能设置一个复选框(左上方的复选框)。问题是我不知道如何解决这个问题,因为Javascript 从父级刷新子级状态,javascript,reactjs,refluxjs,Javascript,Reactjs,Refluxjs,我有一个包含一些数据的表,表中的每个元素都是React类组件。看起来是这样的: 我只想为“全部检查”功能设置一个复选框(左上方的复选框)。问题是我不知道如何解决这个问题,因为props和state 我在单元素组件中有这样的代码: getInitialState: function() { return { component: this.props.data }; }, render: function() { var data = this.state.componen
props
和state
我在单元素组件中有这样的代码:
getInitialState: function() {
return { component: this.props.data };
},
render: function() {
var data = this.state.component;
data = data.set('checked', this.props.data.get('checked'));
...
}
我知道我不应该从props
检查参数,但这只是暂时的
我的问题是:当我在父级中更新选中的参数时,它不会更新状态,因为刷新后不会调用getInitialState
(是的,我知道应该是这样)
我的问题是:我可以更新子组件的状态吗?或者这是实现这一点的更好方法。我的方法是,在父级渲染中,您应该有这样的结构:
<ParentView>
{ this.props.rows.map(function(row) {
<ChildRow props={row.props} />
}).bind(this)
}
</ParentView>
(React文档中的信息:在此函数中调用this.setState()不会触发其他渲染。)
子元素的渲染类似于:
<div>
<input type='checkbox' checked={this.state.isChecked} />
<label>{this.props.label}</label>
</div>
{this.props.label}
您可以通过仅在父元素中存储所有子元素的选中状态来解决此问题。子对象仅基于道具设置其选中状态(不使用状态),并调用父对象提供的回调来更改此状态
例如,在儿童中:
render: function() {
//... not showing other components...
<input type="checkbox"
value={this.props.value}
checked={this.props.checked}
onClick={this.props.onClick}>
}
--未检查打字错误等。请查看提升状态。
在子组件中,您需要使用道具。要更新道具,您需要从父级提供更新功能。带有功能组件:
通过useffect()
,当父级更改提供道具时,刷新子级内部状态的简单方法是:
在儿童方面:
const [data, setData] = useState(props.data);
useEffect( () => {
setData(props.data);
}, [props.data]);
这样,每次道具.data
更改时,都会触发useEffect并强制为某些数据设置新状态,因此组件将“刷新”。除非您非常小心,否则可能会导致子组件与其父组件争夺对其状态的控制权。嗯,最好让孩子成为无状态的,并且只由道具驱动。家长可以控制所有孩子的检查状态。@edoloughlin谢谢你的评论,它救了我的命。是的,这就是我想要的。非常感谢。
getInitialState: function() {
return {
allChecked: false,
childrenChecked: new Array(NUM_CHILDREN) // initialise this somewhere (from props?)
}
},
render: function() {
return <div>
<input type="checkbox" checked={this.state.allChecked}>
{children.map(function(child, i) {
return <Child checked={this.state.childrenChecked[i]}
onClick={function(index) {
return function() {
// update this.state.allChecked and this.state.childrenChecked[index]
}.bind(this)
}.bind(this)(i)}
/>
}).bind(this)}
</div>;
}
const [data, setData] = useState(props.data);
useEffect( () => {
setData(props.data);
}, [props.data]);