1

我在一个项目中使用redux,在返回一个端点后,我在状态中添加了一个值,然后我需要使用这个状态中的值来发送另一个请求。

作为保存值的路径是这样的:

form.state.code.code

我这样做了:

const getValue = await getState().form.state.code.code ? getState().form.state.code.code : null;

我做了这个条件来检查状态中是否有任何值,如果它不存在,它应该返回 null

此代码有效,但我发现它非常冗长,有什么办法可以改进它吗?

4

1 回答 1

1

使用对象解构

const {form: {state: {code = null} = null} = null} = await getState();
const getValue = code && code.code ? code.code : null;

或者你不需要使用 await getState,你可以使用 optional-chaning 来实现

const getEL = getState()
const getValue = getEL && getEL.form && getEL.form.state && getEL.form.state.code && getEL.form.state.code.code
于 2021-07-22T19:19:15.053 回答