[英]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.