简体   繁体   English

如何在反应组件回调后传递新的道具?

[英]How to pass new props after callback in react component?

I need to pass new props to child when callback was called in other child in this component. 当在此组件中的其他子进程中调用回调时,我需要将新的props传递给child。 Here is a sample with setState() , which is doesn't work correctly. 以下是setState()的示例,该示例无法正常工作。 How i can do this? 我怎么能这样做? Ie bool value from onChange to isExpanded . 即从onChangeisExpanded bool值。

export default class Item extends React.Component {

constructor(props) {
    super(props);

    this.state = {
        isExpanded: false,
    };

    this.handleChange = this.handleChange.bind(this);
}

render() {
    const {
        id,
        title,
    } = this.props;

    return (
        <ExpansionPanel onChange={this.handleChange}>
            <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
                <Typography>{title}</Typography>
            </ExpansionPanelSummary>

            <ExpansionPanelDetails>
                <Program isExpanded={this.state.isExpanded} id={id}/>
            </ExpansionPanelDetails>
        </ExpansionPanel>
    )
}

handleChange = (event, expanded) => {
    this.setState({isExpanded: expanded});
}

} }

I expanded it, Program receive false: console log 我扩展了它,程序收到错误: 控制台日志

I closed it, Program receive true: console log 我关闭它,程序收到true: 控制台日志

onChange doesn't provide expanded parameter and there's no need for it, because derived state should be set with state updater function and current isExpanded value is available there: onChange不提供expanded参数,也不需要它,因为派生状态应该用状态更新器功能设置,并且当前的isExpanded值可用:

handleChange = (event) => {
    this.setState(state => ({isExpanded: !state.isExpanded}));
}

Problem was in Program component, which using componentWillReceiveProps . 问题出在Program组件中,它使用componentWillReceiveProps I just used newProps and it works fine. 我刚刚使用newProps ,它工作正常。 Here is working componentWillReceiveProps from Program : 这是来自Program工作componentWillReceiveProps

componentWillReceiveProps(nextProps) {
    const {
        id,
        program,
        fetchData,
    } = this.props;

    console.log("isExpanded: ", nextProps.isExpanded)

    if(nextProps.isExpanded && !program[id]) {
        fetchData(id);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM