繁体   English   中英

从 props 值重新分配状态

[英]Reassigning state from props value

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

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

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

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. 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 时,更新状态的正确方法是什么?

它应该是:

setLegendChoice(event.target.value)

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

value={legendChoice}

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

弄清楚了

异步调用和状态更新不能很好地结合在一起,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])

我的 API 调用现在每次在legendChoice上有状态更新时legendChoice

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM