我正在一个基本上由以下主要组件设置的环境中工作:
class MainComponent extends Component {
constructor(props) {
super(props);
this.state = {
selectedValues: []
};
}
render() {
const { selectedValues } = this.state;
return (
// Other components
<SubComponent selectedValues = {selectedValues} />
// Other components
);
}
}
export default MainComponent;
还有这样的子组件:
class SubComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isExporting: false,
selectedValues: props.selectedValues
};
}
performTask = () => {
this.setState({ isWorking: true });
const { selectedValues } = this.state;
console.log(`Selected Values: ${selectedValues}`);
fetch('/api/work', {
method: 'GET'
})
.then(res => res.json())
.then((result) => {
// Handle the result
this.setState({ isWorking: false });
})
.catch((error) => {
console.log(error);
this.setState({ isWorking: false });
});
};
render() {
const { isWorking } = this.state;
return (
<Button
bsStyle="primary"
disabled={isWorking}
onClick={() => this.performTask()}
>
{isWorking ? 'Working...' : 'Work'}
</Button>
);
}
}
SubComponent.propTypes = {
selectedValues: PropTypes.arrayOf(PropTypes.string)
};
SubComponent.defaultProps = {
selectedValues: []
};
export default SubComponent;
在主组件中,还有其他一些组件可以更改selectedValues
。我想看到的功能是,在触发performTask
方法时,它具有selectedValues
的最新列表。在我当前的设置中,selectedValues
始终是一个空列表。无论实际上在主组件中选择了多少个值,列表在子组件中似乎都没有改变。
有一种简单的方法吗?
答案 0 :(得分:0)
我建议您使用以下两种方法来检查此问题:
this.props.selectedItems
,则可能会起作用。WillReceiveProps(newProps)
添加到子组件并检查其中的值。
如果此方法未调用,则表示selectedItems不变。如果其中一些有效,请更新。
祝你好运。
答案 1 :(得分:0)
selectedValues 尚未更新。您可能需要在SubComponent的componentWillReceivedProps中再次调用setState