Nested React component not updating ‘grandchilds’

huangapple go评论66阅读模式
英文:

Nested React component not updating 'grandchilds'

问题

我有3个嵌套的选择项:国家 -> 州 -> 城市。

但是当我更改国家时,州会更新,但城市不会。

代码:
https://codesandbox.io/s/change-a-selects-options-based-on-another-dropdown-using-react-forked-hjfr2m?file=/src/App.js

英文:

I have 3 nested selects: Country -> State -> City.

But when I change the Country, the State is updated but not the City.

The code:
https://codesandbox.io/s/change-a-selects-options-based-on-another-dropdown-using-react-forked-hjfr2m?file=/src/App.js

答案1

得分: 0

那是正确的。当您更改国家时,State中的onChange会触发。

<select onChange={handleChange}>{options}</select>

因此,它会更改该值。由于您没有触发State,城市保持不变。

英文:

That is correct. When you change country, onChange in State

&lt;select onChange={handleChange}&gt;{options}&lt;/select&gt;

gets triggered. So it changes the value. Since you are not triggering State, City is untouched

答案2

得分: 0

你可以在你的 Category 组件中添加一个 useEffect

useEffect(() => {
  if (category) setSelected(category.options[0])
}, [category])
英文:

You can add a useEffect in your Category component :

useEffect(()=&gt; {
  if (category) setSelected(category.options[0])
}, [category])

huangapple
  • 本文由 发表于 2023年3月31日 04:55:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定