我有带有函数 SearchArticle() 的组件搜索器,它在组件安装后正确使用 this.state.search 和 DEFAULT 值(控制台显示 Searching...:DEFAULT)。但是,当我使用 handleKeyPress(e) 更新 this.state.search 时,它们相同的函数 SearchArticle() 在更新为 e.target 值之前使用 prev 状态(控制台再次显示 Searching...:DEFAULT)。不知道如何修复它。

class Searcher extends Component {

    constructor(props) {
        super(props);
        this.state = {
            article: [], search: "DEFAULT"
        };
    }

    searchArticle() {
        console.log('Searching...: ', this.state.search)
    }

    handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            this.setState({search: e.target.value});
            this.searchArticle();
        }
    }

    componentDidMount() {
        this.searchArticle();
    }

    render() {
        return (
            <div className="row">
            Search: <input onKeyPress={this.handleKeyPress} type="text" />
            </div>
        )
    }

}

最佳答案

很可能在执行 console.log 时状态尚未更新。这是因为 setState() 是异步的。
所以试试这个:

handleKeyPress = (e) => {
  if (e.key === 'Enter') {
    this.setState({search: e.target.value}, () => {
       this.searchArticle();
    });
  }
}
我将您的 searchArticle() 移动到 setState() 回调中。这将保证在状态实际更新后执行。

阅读更多关于 setState() here 的信息。

关于reactjs - 如何在 React 中通过事件处理程序更新和使用状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43761819/

10-16 23:43