首页 > 解决方案 > 根据 Child 组件更新 App 状态

问题描述

在更新我在其中执行请求的组件的状态时,我需要更新父组件 ( App.js ) 的状态。ChildGETcomponentDidMount()

我试图将函数setPoints作为道具传递,但不幸的是这不起作用。

这是我尝试过的:

Child零件 :

class Child extends Component {

    state = {
        points: null
    }

    async componentDidMount() {
        try {
            const res = await axios.get(url);
            const data = res.data;
            this.setState({
                points: data.points,
            })
            this.props.setPoints();
        } catch (err) {
            console.log('child', err);
        }
    }

    render() {
        return (
            <div>
            </div>
        );
    }
}

父组件 ( App):

class App extends Component {

    state = {
        points: '',
    }

    setPoints() {
        this.setState({
            ...this.state,
            points: this.state.points
        });
    }

    shouldComponentUpdate(nextState) {
        if (this.state.points !== nextState.points) {
            return true;
        }
        return false;
    }

    render() {
        return (
            <div className="App">
                <Route exact path="/child" render={() => <Child setPoints={this.setPoints} />} />
            </div>
        );
    }
}

谁能帮我解决这个问题?帮助将不胜感激。

编辑

我尝试了 Joe Clay 写的内容,这很有意义,但我仍然遇到错误。这是我更新的代码:

    async componentDidMount() {
    try {
        const res = await axios.get(url);
        const data = res.data;
        console.log(data.points);
        this.props.setPoints(data.points);
    } catch (err) {
        console.log('child', err);
    }

它确实记录了点的值,但由于某种原因,我得到:“无法读取未定义的属性'点'”。

标签: reactjsasync-awaitparent-childreact-props

解决方案


考虑父组件中数据的值。我将通过将道具传递给在父组件中执行 setState 的函数来更改数据的值,从而将值更改为所需的值。

父组件

class Parent extends React.Component{    
    constructor(props){
         super(props);
         this.state({
             name:''
         })
    }    

     handleChange(value){
         this.setState({name:value});
     }
     render(){
         return (<Child handleChange={this.handleChange} />)
     }
}

将 handleChange 函数作为道具传递给子组件。

子组件

export default class Child extends React.Component{
     sendData(false){
        this.props.handleChange(hello)   //make sure to pass the value in the 
          argument that you wish to do a setState on in the parent component
     }   
}

这将在父组件中将 name 的值设置为 hello。


推荐阅读