反应-子组件未在父组件上设置状态?

时间:2020-06-16 22:42:50

标签: reactjs

我有一个App父组件和一个子Create组件。

我从SO中的其他线程中读取,我必须创建一个在父组件上设置状态的方法,并将其作为道具传递给子代。

在我的情况下,我在父级中有一个名为post的方法,并传递给了子级Create组件,该组件在单击按钮时被调用。

单击该按钮时,结果表明它甚至无法读取状态,因为其状态未定义。 感谢我能得到的任何输入。

父组件

class App extends React.Component {
    state = {
        products: []
    }

    post(name){ //post method to be passed into Create component as props
        return axios.post(`http://localhost:3000/api/products/${uuidv4()}`, {id: uuidv4(), name: name })
        .then(res => this.setState({products: [res.data, ...products]})) //console.log(this.state) will return Cannot read property state of undefined.
        .catch(error => console.log(error));
    }

    render(){
        const {products} = this.state;       
        return( //pass this.post to Create component
            <div>
                <Create post={this.post}/>
            </div>
        )
    }
}

子组件

class Create extends React.Component {
    state = {
        inputValue: '',
    }

    updateInput(value){
        this.setState({inputValue: value});
    }

    render(){
        const {inputValue} = this.state;
        const {post} = this.props; //destructure post method from App component
        return( // called post method inside the button onClick
        <div className='form'>
            <input type='text' value={inputValue} onChange={(event)=>this.updateInput(event.target.value)}/>
            <button onClick={() => post(inputValue)}>Create</button> 
        </div>
        )
    }
}

2 个答案:

答案 0 :(得分:1)

在您的父组件中,如下更改:

<Create post={(input) => {
    this.post(input);
}}/>

您需要这样做的原因是,在子组件中调用post的方式意味着它没有“作用域”到父组件。

答案 1 :(得分:0)

const post = (name) => {
    ....
}

(使用箭头函数在组件构造函数中不对该函数使用绑定)

<button onClick={() => post(this.state.inputValue)}>Create</button> 

(我认为需要this.state来检索inputValue状态属性)