【发布时间】: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