简体   繁体   中英

What's the reason for not getting the variable I'm expecting in the functional component?

I'm familiar with useState hook for storing variables that change and need to reload the component. Are variables not local to each function call? For example, I have a functional component that I passed ticket information to. I take that information store it in a variable and pass it to another screen. That component is render in a flat list depending on which one is called I want to store that value and pass it to another screen. My problem is, that value is getting stored in the local object but only the value of the last item rendered not the one pressed. Here is my code:

If I save ticket from params, update it with the "siteCode", and pass it in the params of the onPress event, I don't get the results i'm looking for. If i pass siteCode outside of the custom object I get the results I'm looking for. I just want to understand what I'm missing here. Do i still need to use the useState hook even though i'm not looking to render the component again? Thanks

You are breaking the contract, so unfortunately you get whatever you get. And since it's not a supported use case you sadly can't expect it not to change in different React versions either.

React expects a pure functional component to be, well, a pure, functional, component (referentially transparent, no side effects). You are mutating your props, which as I said is not supported (this seems to come up a lot on github issues on the React repo).

In ye olden days, if your component was not pure you used a class. Now we have hooks, but the hook is essentially a clever workaround: because React knows about the hooks you don't violate the functional component contract. But that doesn't mean anything goes, if you have a side effect (like mutating an object defined elsewhere) then you need to put it in a hook or screwy things will happen.

NB even in a class, or even outside of React entirely, it's rarely (never?) a good idea to mutate the parameter to a function unless that mutation is the only thing the function does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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