首页 > 解决方案 > React Select 值未在状态更改时重置

问题描述

我有一个选择组件需要在用户单击下一步按钮后重置为“中性”状态。然而,它只是继续显示用户之前选择的内容。我将它们拆分为如下所述的组件。您可以看到按下下一个按钮时,defaultValue 重置为“3”,但这似乎仅适用于组件首次呈现时,并且在随后的按下时不再适用。

const QuestionLikert = ({ nextQuestion, prevQuestion, setLikertResponse, likertResponse }) => {

  return (
<div className='section'>
  <div className='container'>
    <div>
        <div>
          <select
            id='response'
            name='response'
            onChange={setLikertResponse}
            defaultValue={likertResponse}
          >
            <option value="1">Strongly Disagree</option>
            <option value="2">Disagree</option>
            <option value="3">Neutral</option>
            <option value="4">Agree</option>
            <option value="5">Strongly Agree</option>
          </select>
        </div>
      <button onClick={nextQuestion}>
        Next
      </button>
      <div>
        <span onClick={prevQuestion}>Back </span>
      </div>
    </div>
  </div>
</div>
)}

const ParentComponent = () => {

  const [currentQuestion, setCurrentQuestion] = useState(0)

  const [likertResponse, setLikertReponse] = useState('3')

  const handleLikertInput = (e) => {
    setLikertReponse(e.target.value)
  }

  const toggleNextQuestion = () => {
    setLikertReponse('3')
    setCurrentQuestion(currentQuestion + 1)
  }
  const togglePrevQuestion = () => {
    setCurrentQuestion(currentQuestion - 1)
  }

  return (
    <Layout>
      <div className='section'>
        <div className='container'>
          <div>
              <QuestionLikert 
                nextQuestion={toggleNextQuestion} 
                prevQuestion={togglePrevQuestion}
                setLikertResponse={handleLikertInput}
                likertResponse={likertResponse}
              />
          </div>
        </div>
      </div>
    </Layout>
  )
}   

标签: javascriptreactjsuse-effect

解决方案


<select>值参数QuestionLikert应该由likertResponse道具控制,因为它的状态来自ParentComponent

<select
  id='response'
  name='response'
  onChange={setLikertResponse}
  value={likertResponse}
>
  <option value="1">Strongly Disagree</option>
  <option value="2">Disagree</option>
  <option value="3">Neutral</option>
  <option value="4">Agree</option>
  <option value="5">Strongly Agree</option>
</select>

编辑 elated-leakey-gij5z


推荐阅读