javascript - 输入上的 onChange 不使用 setState 更新状态
问题描述
我已经声明了存储数组,例如 ['X', 'XL'] 但我的代码不起作用我不知道为什么?
class App extends Component {
state = {
shirtsSize: ['X', 'XL']
}
handleChange = index => e => {
const { shirtsSize } = this.state
this.setState({
[`${shirtsSize[index]}`]: e.target.value
})
}
render() {
const { shirtsSize } = this.state
return (
<div className="App">
<label htmlFor="shirtsSize">Sizes</label>
<button>+</button>
{shirtsSize.map((lang, index) => (
<input
type="text"
name="shirtsSize"
id="shirtsSize"
value={lang}
onChange={this.handleChange(index)}
/>
))}
</div>
)
}
}
无法找出错误在哪里。
解决方案
和
this.setState({
[`${shirtsSize[index]}`]: e.target.value
})
你不是在更新shirtSize
数组中的数据,而是创建一个新的键shortsSize[0]
,等等。您需要像这样更新数组
const value = e.target.value;
this.setState(prevState => ({
shirtsSize: [...prevState.shirtsSize.slice(0, index), value, ...prevState.shirtsSize.slice(index + 1) ]
}))
或者干脆
const shirtsSize = [...this.state.shirtsSize];
shirtsSize[index] = e.target.value
this.setState({
shirtsSize
})
推荐阅读
- sql - SQL - 检查项目在上个月是否可用,然后标记它
- flutter - 如何同步dart中异步函数的调用
- sql - 如何在分组和排序时调整查询以显示前 5 个
- javascript - 卡在 OOP 计算器中的括号(不使用 Eval)
- javascript - 如何在 Typescript 中获得后期绑定
- matlab - 拉盖尔求多根的方法(Matlab)
- react-native - React Navigation poptotop 并在一个动画中移动到下一个屏幕
- azure - Azure DevOps 查询工作项(如果有任何父项正在进行)
- java - 无限期休眠的守护线程的目的
- c# - 如何通过office open xml标准创建/编辑excel