React类组件中Enter事件触发后state值未实时更新问题求助
解决React Select Creatable组件按下Enter时无法获取最新值的问题
我明白你遇到的困扰了——按下Enter键添加新值时,console.log("vvvv", value)打印的还是旧的数组,这是因为React的setState是异步操作,不会立刻更新组件的state。
问题根源
当你执行this.setState({ inputValue: "", value: [...value, createOption(inputValue)] })时,React会把这个状态更新加入队列,不会马上修改this.state。所以在同一个事件处理函数里,紧接着的console.log拿到的还是更新前的value值。
两种可行解决方案
方案1:利用setState的回调函数获取最新值
setState支持第二个参数,这是一个状态更新完成后的回调函数,在这个函数里可以安全地拿到最新的state:
handleKeyDown = (event: SyntheticKeyboardEvent<HTMLElement>) => { const { inputValue, value } = this.state; if (!inputValue) return; switch (event.key) { case "Enter": const newValue = [...value, createOption(inputValue)]; console.log("vvvv", newValue); break; // 记得加break避免执行后续Tab的逻辑 case "Tab": const newTabValue = [...value, createOption(inputValue)]; console.group("Value Added"); console.log(newTabValue); console.groupEnd(); this.setState({ inputValue: "", value: newTabValue }, () => { // 回调内获取最新state console.log("最新value:", this.state.value); }); event.preventDefault(); } };
方案2:提前构建新值再使用
在调用setState之前,先手动构建好包含新值的数组,之后直接使用这个数组即可:
handleKeyDown = (event: SyntheticKeyboardEvent<HTMLElement>) => { const { inputValue, value } = this.state; if (!inputValue) return; // 提前创建好包含新值的数组 const newValue = [...value, createOption(inputValue)]; switch (event.key) { case "Enter": console.log("vvvv", newValue); // 直接用新数组,拿到最新值 break; case "Tab": console.group("Value Added"); console.log(newValue); console.groupEnd(); this.setState({ inputValue: "", value: newValue }); event.preventDefault(); } };
另外注意:你的原代码里case "Enter"没有加break,会导致case "Tab"里的代码也被执行,如果你不需要这个逻辑,一定要加上break哦。
这样修改后,你就能在按下Enter时立刻获取到包含新值的数组了。
内容的提问来源于stack exchange,提问作者Asking
相关产品推荐
相关产品推荐

