简体   繁体   English

如何在 useState 和 useEffect 中设置初始状态

[英]How to set initial state in useState and useEffect

I might be not understanding completely the principals oh useState hook and there is a problem I came across a few times now.我可能不完全理解原则哦useState hook 并且我现在遇到了几次问题。

I'm trying to set an initial state in my component using useEffect without dependencies and later on compare it to some other variables I get from redux .我正在尝试使用没有依赖关系的useEffect在我的组件中设置初始状态,然后将其与我从redux获得的其他一些变量进行比较。

// get the customer saved in redux
const Customer = useGetCustomer();

const [prevCustomerNumber, setPrevCustomerNumber] = useState(null)

useEffect(() => {
// if there is already customer saved in redux, set it as the previous customer on mount
    const { CustomerNumber } = Customer || {}
    setPrevCustomerNumber(CustomerNumber)
}, [])

const submit = () => {
//check if there is any change between the customer in redux and the previous one
  const { CustomerNumber } = Customer || {}
  const submitWithoutChanges = Customer && ( CustomerNumber === prevCustomerNumber)
  submitCustomer(Customer, submitWithoutChanges )
}

My problem is - when clicking submit, prevCustomerNumber is always null.我的问题是 - 单击提交时, prevCustomerNumber始终为空。 My questions are:我的问题是:

  1. Is it because useState runs again after the first useEffect and override it?是不是因为useState在第一个useEffect之后再次运行并覆盖它?
  2. What should I do to save initial state properly?我应该怎么做才能正确保存初始状态?

您可以将 prevCustomerNumber 的初始状态设置为

const [prevCustomerNumber, setPrevCustomerNumber] = useState("some value")

Your problem is that you get the customer from redux only when the component renders.您的问题是只有在组件呈现时才从 redux 中获取客户。 When you click submit button, the function does not tries to read the data from redux again and only uses the data that already has which may be wrong or null.当您单击提交按钮时,该函数不会再次尝试从 redux 中读取数据,而只会使用已有的数据,这些数据可能是错误的或为空的。 In order to have the latest data from redux store you need to wrap your component with the Connect function:为了从 redux 存储中获得最新数据,您需要使用Connect函数包装您的组件:

export default connect ((state) => {
  const customerNumber = state.customer.customerNumber
  return {customerNumber}
})(YourComponent)

YourComponent will now receive the customerNumber props every time your redux store changes.每次您的 redux 存储更改时,您的组件现在都会收到 customerNumber 道具。

Or if you prefer hooks you can use useSelector hook:或者,如果你更喜欢钩子,你可以使用useSelector钩子:

import { useSelector } from 'react-redux'
const customerNumber = useSelector(state => state.customer.customerNumber)

Now every times the components renders or the redux store changes the useSelector hook will return the update value现在每次组件渲染或 redux 存储更改时 useSelector 钩子将返回更新值

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

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