【问题标题】:Update App state based on Child component根据 Child 组件更新 App 状态
【发布时间】:2018-06-14 20:29:36
【问题描述】:

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

我尝试将函数 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);
    }

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

【问题讨论】:

  • 请阅读 React 文档网站上的 Lifting State UpThinking in React。将相同的状态存储在两个单独的组件中几乎总是表明您以错误的方式处理事情 - 惯用的 React 代码通常对于任何给定的数据都有“单一事实来源”。
  • 另外请阅读关于使用更新函数reactjs.org/docs/react-component.html#setstate根据当前状态计算的设置状态

标签: reactjs async-await parent-child react-props


【解决方案1】:

考虑父组件中数据的值。我将通过将道具传递给在父组件中执行 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 函数作为 prop 传递给子组件。

子组件

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。

【讨论】:

    【解决方案2】:

    关于孩子:

    this.props.setPoints(data.points)
    

    在父级上:

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

    【讨论】:

    • 谢谢,我确实这样做了,这是有道理的,不幸的是,请求捕获了这个错误:“无法读取未定义的属性'点'”。
    • console.log(res.data) 检查结果正常
    • 日志确实有效,所以我无法弄清楚为什么会出现此错误
    • 表示数据未定义。可以在这里发送 axios 结果的控制台日志吗?
    • 感谢您的帮助。我改用 Ercik 的解决方案,效果很好。我仍然不知道 setPoints 中的参数有什么问题......
    猜你喜欢
    • 2021-09-25
    • 2019-10-23
    • 1970-01-01
    • 2021-01-12
    • 2021-06-25
    • 1970-01-01
    • 2017-11-27
    • 2018-11-23
    • 2016-03-16
    相关资源
    最近更新 更多