【问题标题】:Reassigning state from props value从道具值重新分配状态
【发布时间】:2020-03-25 20:22:05
【问题描述】:

我有一个 Select 组件,一旦单击一个选项,该值就会向上传递到父组件。

父组件有一个初始值来渲染应用程序,但我希望一旦它通过 props 接收到新值,就可以更改该值。

我的子组件有一个 onChange 接收 prop 并将其传递给父组件

const AxesChoice = ({ legendChoice, xChoice, updateAxis, updateLegend }) => {
  const [labels, updateLabels] = useState([])

  const { Option } = Select


  return (
    <div>
     <Select
        key="legendChoice"
        style={{ width: 250 }}
        value={legendChoice}
        onChange={event => {
          updateLegend(event)
        }}
      >
        {labels.map(items => (
          <Option key={items} value={items.header}>
            {items.label}
          </Option>
        ))}
      </Select>
    </div>
  )
}

在我的父组件中,子组件是这样渲染的

 <AxesChoice
        xChoice={axisChoice}
        legendChoice={legendChoice}
        updateAxis={updateAxisChoice}
        updateLegend={updateLegendChoice}
      />

初始状态值是这样设置的

  const [legendChoice, setLegendChoice] = useState('qualified')

要更新 legendChoice 我有一个函数

const updateLegendChoice = event => {
    console.log('fired', event)
    // legendChoice = event
    console.log('legendCHoice', legendChoice)
    console.log('event', event)
    setLegendChoice({ legendChoice: event })
    console.log('newLegend', legendChoice)
    axios
      .get(`${BASE_URL}/${axisChoice}/${legendChoice}/${yearChoice}`)
      .then(res => setState(res.data.data))
      .catch(error => console.log(error))
    console.log('newState', state)
  }

此时应用程序崩溃并出现几个警告 Uncaught Error: Objects are not valid as a React child (found: object with keys {legendChoice}). If you meant to render a collection of children, use an array instead.

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

我已经尝试通过这样做来更新legendChoice

setLegendChoice(event)

但是这个输出

legendCHoice qualified
event role
newLegend qualified

当值来自props时更新状态的正确方法是什么?

【问题讨论】:

    标签: javascript reactjs oop state react-hooks


    【解决方案1】:

    应该是:

    setLegendChoice(event.target.value)
    

    当您使用 set 函数时,它只接受值,它知道该值正在应用于 LegendChoice。可以肯定的是,您实际上是在设置 legendChoice = {legendChoice: yourvalue},所以当您在这里调用 legendChoice 时:

    value={legendChoice}
    

    你把值等于一个对象,而不是一个字符串。

    【讨论】:

      【解决方案2】:

      想通了

      异步调用和状态更新不能很好地配合使用,useEffect 挂钩解决了这个问题

      我的函数现在看起来像这样

      const updateLegendChoice = value => {
          setLegendChoice(value)
        }
      

      我已将 API 调用移出函数并将其移至 useEffect Hook

      useEffect(() => {
          axios
            .get(`${BASE_URL}/${axisChoice}/${legendChoice}/${yearChoice}`)
            .then(res => setState(res.data.data))
            .catch(error => console.log(error))
        }, [legendChoice])
      

      现在每次legendChoice 有状态更新时都会触发我的 API 调用。

      【讨论】:

      • 你应该单独使用/传递event.target.value 而不是event(对象)
      • event 在这种情况下实际上是一个字符串,而不是一个对象。我已将 event 更改为 value 以提高可读性
      猜你喜欢
      • 1970-01-01
      • 2023-01-28
      • 2015-07-16
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多