javascript - React 更新父组件

标签 javascript reactjs

我有一个 React 组件,当我在子组件上调用 onSubmit 时需要更新该组件

需要更新的父组件如下所示:

componentDidMount() {
    axios.get('/todo')
        .then(function (response) {
            this.setState({
                todoList: response.data
            })
        }.bind(this))
        .catch(function (error) {
            console.log(error);
        });
}

render() {
    return (
        <div>
            <Form/>
            {this.state.todoList.map(todo => {
                return (
                    <TodoItem
                        id={todo._id}
                        key={todo._id}
                        itemToDo={todo.todoItem}

                    />
                );
            })}
        </div>
    )
  }

当我提交<Form/>时我调用的组件

handleSubmit(e) {
    e.preventDefault();
    axios.post('/todo', {
        todoItem: this.state.todoItem
    })
}

我需要更新父组件,以便从服务器获取更新的列表

最佳答案

我不完全确定你的问题,但你可以将函数(updateParent)作为属性从父组件传递到子组件,当你想更新父组件时,在子组件中调用 this.props.propFromParentComponent 。如果您希望父组件更新,请使用 this.setState({..}) 并更新组件的状态,以更新此函数内的父组件(updateParent)。

关于javascript - React 更新父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45196682/

相关文章:

javascript - 以编程方式更改 Redux-Form 复选框字段值

javascript - 构建 bash 命令时如何防止注入(inject)攻击?

javascript - 如何在 python 中使用 selenium 驱动程序单击链接而不知道 anchor 标记内的文本

javascript - 使用 gatsby-plugin-sitemap 仅生成一个页面到站点地图

javascript - Facebook 与 javascript FB Graph api 集成 在墙上发布 Firefox 中的未知错误

reactjs - 警告 jsx-a11y/img-has-alt

javascript - 从同一个类获取不同的内部 html

reactjs - tabIndex 专注于 anchor 标签内的内部 React 组件

reactjs - 传递给函数的样式属性的类型

javascript - react 状态更新不正确