javascript - React - 状态不一致

标签 javascript meteor reactjs

我想要实现的目标:将数据从子级传递给父级。

我如何实现它:使用this.state如上所述here

不知道如何表达标题:当我 console.log(this.state)在我修改状态的函数中,this.state中的正确值被打印出来。但是,当我尝试读取另一个函数中的状态时,this.state显然仍为空值。

constructor(props) {
    super(props);
    this.state = {
      titleInputValue: "",
    };
}

<form onSubmit={this.handleSubmit.bind(this)}>
    <TextInput
        val={this.state.titleInputValue}
        changeHandler={this.textInputChangeHandler} />
</form>


// This is the function which can apparently only get the initial state
// title and body are empty strings, they should have values
handleSubmit(event) {
    event.preventDefault();
    const title = this.state.titleInputValue;
    const body = this.state.bodyInputValue;
    console.log(this.state);
    Meteor.call('stories.insert',title,body);
}

// However, here the state is retrieved just fine.
// This is the function the child calls to update the state.
textInputChangeHandler(event) {
    // This console.log call shows the correct state!
    console.log(this.state);
    this.setState({
      titleInputValue: event.target.value,
    });
}

TextInput具有属性onChange={this.props.changeHandler.bind(this)}

举例说明:

enter image description here

我写了asd ,并在 textInputChangeHandler 中成功检索到状态,这是前两个 console.log调用,但 handleSubmit 中为空.

最佳答案

这是因为事件处理程序范围不是组件类级别。当您的组件处理事件时,它的上下文是组件(在您的例子中是 TextInput )而不是父组件。

您必须将该函数绑定(bind)到 Component 类范围的 this 上:

<TextInput
        val={this.state.titleInputValue}
        changeHandler={this.textInputChangeHandler.bind(this) } />

使用 JavaScript 绑定(bind),您还可以指定函数上下文。

关于javascript - React - 状态不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364432/

相关文章:

javascript - 在 Express.js 中外部化 route.param() 调用

javascript - 如何用javascript表达3cos(30)?

javascript - Swipe.js 在 Meteor 中不起作用

javascript - Meteor 无法更新 mongo?

reactjs - 在 React-bootstrap 的 OverlayTrigger 放置属性上使用字符串变量时出现问题

javascript - 在 React 中,如何在多个选择下拉菜单之间更新状态,每个下拉菜单都有相同的选项?

javascript - 更新 API 字符串

javascript - Eloquent Javascript - ch4 - arraytoList - 递归

javascript - Meteor router for multiple layouts 为家庭使用不同的布局

javascript - 当状态改变时更新 React 组件,使用对自身的引用