this.setState 在使用回调函数时不会在 Child 中更新父级



我有一个选择表单子组件,用户可以从中选择多个选项。每次用户做出选择时,都会执行一个函数句柄更改,该函数从父级调用函数 changeExport(作为道具传递给子级(。然后,更改导出更新父状态,并通过更新子状态来处理更改完成。问题是,如果父状态被更新,子状态不是,但是如果我注释掉更新父状态的行,子状态更新得很好。

这是父级。

class ExtendedTable extends React.Component {
constructor(props) {
super(props)
// columnJSON el format is { title: str, field: str, export: bool }
this.state = { dataJSON: [], columnJSON: [] }
this.changeExport = this.changeExport.bind(this)
}
changeExport(titles){
const newColumnJSON = JSON.parse(JSON.stringify(this.state.columnJSON));
newColumnJSON.forEach(col => {
if (titles.indexOf(col.title) >= 0) {
col.export = true
}
else {
col.export = false
}
})
this.setState({ columnJSON: newColumnJSON })
}
render(){return(
....
<MultipleSelect names={this.state.columnJSON.map(el=>el.title)}   export={this.changeExport} />
)}

这就是孩子。

class  MultipleSelect extends React.Component {
constructor(props){
super(props)
this.state = {
names:this.props.names,
column:[]}
this.handleChange = this.handleChange.bind(this)

}
handleChange(event){
const arr = event.target.value.slice()
this.setState({column:arr})
this.props.export(arr)
}
render() {  return(
<div>
<FormControl>
<InputLabel >Tag</InputLabel>
<Select
multiple
value={this.state.column}
onChange={this.handleChange}
input={<Input />}
renderValue={selected => selected.join(', ')}
MenuProps={MenuProps}
>
{this.state.names.map(col => (
<MenuItem key={col} value={col}>
<Checkbox checked={
this.state.column.indexOf(col) > -1}/>
<ListItemText primary={col} />
</MenuItem>
))}
</Select>
</FormControl>
</div>
)};
}

由于这个原因,你在 React 文档中警告你在这里做的事情——将 props 复制到状态。

链接页面提供了许多替代方案。在你的情况下,我认为你最好通过完全消除状态并仅依靠传入的道具来使MultipleSelect成为受控组件。这可能看起来像这样:

class MultipleSelect extends React.Component {
render() {
return (
<div>
<FormControl>
<InputLabel>Tag</InputLabel>
<Select
multiple
value={this.props.selected}
onChange={this.props.handleChange}
input={<Input />}
renderValue={selected => selected.join(", ")}
MenuProps={MenuProps}
>
{this.props.options.map(col => (
<MenuItem key={col} value={col}>
<Checkbox checked={this.props.selected.indexOf(col) > -1} />
<ListItemText primary={col} />
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
}
}

最新更新