简体   繁体   English

反应useState()不改变第一次渲染中的值(一个对象)

[英]react useState() not changing the value(an object) in the first render

I am using react usestate() and I want to update device state(It is an object)我正在使用 react usestate() 并且我想更新device状态(它是一个对象)

my problem is when ShowRelays component renders for the first time device is an empty object and It does not get updated during first rendering, but for the next renders everything is fine我的问题是当ShowRelays组件第一次渲染时device是空的 object 并且在第一次渲染期间它没有得到更新,但是对于下一次渲染一切都很好

How can I update device state for the first time rendering?如何更新device state 首次渲染?

(sorry for my bad english) (对不起,我的英语不好)

. .

function ShowRelays(props) {

const [device, setDevice] = useState({})

let reduxDevices = useSelector(state => state.devicesReducer.devices)

let findDevice = () => {
    let myDevice = reduxDevices.find(x => x._id === props.id)
    setDevice(prevState => {
        return {
            ...prevState,
            ...myDevice
        }
    })
   
}


useEffect(() => {
    if (props.show) {
        findDevice()
    }
}, [props.show])


return
  (
   <div>
    test
   </div>
  )
}

myDevice object is like: myDevice object 就像:

{active: true, name: "device1", id: "deviceId"}

You can pass a function to your useState-hook which will calculate your initial value for device.您可以将 function 传递给您的 useState-hook,它将计算您的设备初始值。

see lazy init state参见惰性初始化 state

function ShowRelays(props) {
    let reduxDevices = useSelector(state => state.devicesReducer.devices);
    const [device, setDevice] = useState(() => {
        return reduxDevices.find(x => x._id === props.id)
    });

    return <div>test</div>;
}

An other possible solution for your problem without using a separate state could be the following (directly select the right device from your selector function):在不使用单独的 state 的情况下解决您的问题的其他可能解决方案可能如下(直接 select 选择器功能中的正确设备):

function ShowRelays(props) {
    const device = useSelector(state => {
        return state.devicesReducer.devices.find(x => x._id === props.id);
    });
    return <div>test</div>;
}

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

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