【问题标题】:Redux: How to get the state with better codeRedux:如何用更好的代码获取状态
【发布时间】:2021-09-30 01:07:00
【问题描述】:

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

保存值的路径是这样的:

form.state.code.code

我这样做了:

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

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

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

【问题讨论】:

  • 您不需要等待getState。您可以使用 nullsafe-operator(optional-chaining) 来缩短代码。

标签: javascript reactjs redux getstate


【解决方案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-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 2019-10-15
  • 2021-12-10
  • 2018-11-30
  • 2021-08-17
相关资源
最近更新 更多