简体   繁体   English

反应 useState 收到或默认 state

[英]React useState received or default state

I think it is good time to improve something in the code:D我认为现在是改进代码中某些内容的好时机:D

Listen => Code听 => 代码

// props.selectedProduct.quantity = '5'
const [quantity, setQuantity] = useState(props.selectedProduct?.quantity || '1')

Even when I receive quantity = '5' the ||即使我收到quantity = '5'的 || is set the default value to '1'将默认值设置为'1'

Why my Brothers?为什么是我的兄弟们?

How could we improve it?我们如何改进它?

I know that we can do something like props.selectedProduct?.quantity? props.selectedProduct?.quantity: '1'我知道我们可以做类似props.selectedProduct?.quantity? props.selectedProduct?.quantity: '1' props.selectedProduct?.quantity? props.selectedProduct?.quantity: '1' but is there any more smart way to achieve our target/mission to be more happy every day? props.selectedProduct?.quantity? props.selectedProduct?.quantity: '1'但是有没有更聪明的方法来实现我们每天更快乐的目标/使命?

Bless you Devs祝福你们开发者

You are not using useState correctly and this is why you have problems with it.您没有正确使用 useState,这就是您遇到问题的原因。

You DO NOT update the state by forwarding props(.).您不会通过转发 props(.) 来更新 state。

If you want to update a state you use the setState function.如果要更新 state,请使用 setState function。

If you are using your state in multiple childs, you should use Context or any other state managment such as recoil, redux, etc...如果您在多个孩子中使用 state,则应使用 Context 或任何其他 state 管理,例如后坐力、redux 等...

You should learn more about React and React Hooks here: React Docs您应该在此处了解有关 React 和 React Hooks 的更多信息: React Docs

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

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