简体   繁体   English

从子组件中反映父级的更新状态

[英]React update state in parent from child components

I have child components that receive props from a parent, but on an event (button click) in a child I want to setState again with the new props. 我有一个从父领取道具子组件,但在孩子的事件(点击按钮)我想setState新道具一次。 So the parent passes down all items in a list to the children. 因此,父级将列表中的所有项目传递给子级。 In the child prop a button deletes an item in the list. 在子prop中,按钮删除列表中的项。 But how can you update the state so the list item is also removed from the view. 但是如何更新状态以便列表项也从视图中删除。 This is my code: 这是我的代码:

const Parent = React.createClass({
    getInitialState:function(){
        return {
            items: []
        };
    },
    componentWillMount:function(){
        axios.get('/comments')
            .then(function(response) {
                this.setState({
                    items: response.data
                })
            }.bind(this));
    },
    render() {
        return (
            <div>
                <Child1 data={this.state.items}/>
            </div>
        );
    }
});

export default Parent;

export default function Child1(props){
    return(
        <div>
            { props.data.map((comment,id) =>(
                    <p key={id}>
                        {comment.name}<Delete data={comment.id}/>
                    </p>
                )
            )}
        </div>
    )
}

class Delete extends React.Component {
    constructor() {
        super();
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        Purchase.Action(this.props.data,'remove');
        axios.post('/comments', {
            item: this.props.data
        })
        .then(function (response) {
            console.log(response.data);     
        })
        .catch(function (error) {
            console.log(error);
        });
    }

    render() {
        return <Button onClick={this.handleClick}>Delete</Button>;
    }
}

module.exports = Delete;

So although the comment is deleted at the server, I want to delete the comment from the component view by updating the state. 因此,虽然在服务器上删除了注释,但我想通过更新状态从组件视图中删除注释。

If you want to delete the comment from the component, you have to update your Parent state . 如果要从组件中删除注释,则必须更新父state

In order to do that you can create a new method, delete(id) , in your Parent component where you remove the deleted item from the state. 为此,您可以在Parent组件中创建一个新方法delete(id) ,在该组件中从状态中删除已删除的项目。

const Parent = React.createClass({
    getInitialState:function(){
        return {
            items: []
        };
    },
    componentWillMount:function(){
        this.setState({
            items: [
            {id: 1,name: "Name 1"},
            {id: 2,name: "Name 2"},
            {id: 3,name: "Name 3"}
          ]
        })
    },
    delete(id){
      // axios.post(...)
      let items = this.state.items.filter(item => item.id !== id);
      this.setState({items});
    },
    render() {
        return (
            <div>
                <Child1 
                   data={this.state.items} 
                   handleClick={this.delete} // Pass the method here
                />
            </div>
        );
    }
});

function Child1(props){
    return(
        <div>
            { props.data.map((comment,id) =>(
                    <p key={id}>
                        {comment.name}
                        <Delete 
                           data={comment.id}
                           handleClick={() => props.handleClick(comment.id)} // Pass the id here
                        />
                    </p>
                )
            )}
        </div>
    )
}

class Delete extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return <button onClick={this.props.handleClick}>Delete</button>;
    }
}

jsfiddle 的jsfiddle

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

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