Redux:如何用更好的代码获取状态

问题描述

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

保存值的路径是这样的:

form.state.code.code

我这样做了:

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

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

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

解决方法

使用对象解构

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