状态在反应中被覆盖

时间:2020-02-11 21:41:22

标签: javascript reactjs

  <form onChange = {handleFilterChange}>
    <select name="movie">
      <option value="default">Please choose a movie</option>
      {state.data.map(movie => (<option value={movie.title}>{movie.title}</option>))}
    </select>
    <select name="species">
      {state.appliedFilters.movie !== undefined ? [...new Set(species)].map(specie => (<option value={specie}>{specie}</option>)):
      (<option value="default">Please select a movie first)</option>) }
    </select>
  </form>

我上面有这个表格和一个onChange函数:

  const handleFilterChange = (e) => {
    if(e.target.value === 'default' && state.appliedFilters !== undefined){
      setState({...state ,appliedFilters : {}});
    }else{
      setState({...state, appliedFilters:{[e.target.name] : e.target.value}})
    }
  }

当我应用电影滤镜然后对物种进行更改时,选择电影滤镜消失而该物种仅存在。

1 个答案:

答案 0 :(得分:1)

您已经在<form>而非<select>上设置了onChange处理程序,因此event.targetevent.target.value并不是您想要的(这是表单,而不是选择)。

将onChange移至电影<select>

 <form>
    <select name="movie" onChange={handleFilterChange}>
      <option value="default">Please choose a movie</option>
      {state.data.map(movie => (<option value={movie.title}>{movie.title}</option>))}
    </select>
    <select name="species">
      {state.appliedFilters.movie !== undefined ? [...new Set(species)].map(specie => (<option value={specie}>{specie}</option>)):
      (<option value="default">Please select a movie first)</option>) }
    </select>
  </form>