首页 > 解决方案 > 输入上的 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>
    )
  }
}

无法找出错误在哪里。

标签: javascriptreactjsecmascript-6

解决方案


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
    })

推荐阅读