我一直得到:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the SearchInput component.
我尝试过以下这些:
https://facebook.github.io/react/docs/two-way-binding-helpers.html#linkedstatemixin-before-and-after
https://stackoverflow.com/questions/28773839/react-form-onchange-setstate-one-step-behind
问题很简单:当用户在输入字段中键入内容时,通过 onChange
属性和 setState
捕获输入
import React, { Component } from 'react';
class SearchInput extends Component {
constructor() {
super();
this.state = {
inputValue: ''
};
this.onChange = this.onChange.bind(this);
}
render() {
return (
<input
type="text"
value={this.state.inputValue}
onChange={this.onChange} />
);
}
onChange(e) {
console.log('yo');
this.setState({ inputValue: e.target.value });
}
}
export default SearchInput;
如何安装我的组件以便警告消失并且可以更新用户输入状态?
更新
我最近将我的 .babelrc
文件更改为:
{
"presets": ["latest-minimal", "stage-1", "react"],
"plugins": ["react-hot-loader/babel"]
}
如下:https://github.com/gabmontes/babel-preset-latest-minimal
但是一旦我恢复到以前的状态:
{
"presets": ["es2015", "stage-1", "react"],
"plugins": ["react-hot-loader/babel"]
}
警告消失了。
latest-minimal
中的某些内容不活跃。
最佳答案
使用defaultValue代替值。
render() {
return (
<input
type="text"
defaultValue ={this.state.inputValue}
onChange={this.onChange} />
);
}
检查这个不受控制的组件概念:
https://facebook.github.io/react/docs/forms.html#uncontrolled-components
基本上,当您使用表达式设置值时,Input 会保持自己的状态,它会在渲染 SearchInput 组件时触发输入组件(未安装的组件)中的状态更改。
关于javascript - react this.setState 已安装或正在安装时的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40454028/