gpt4 book ai didi

javascript/redux : how to avoid null when fetching state?

转载 作者:行者123 更新时间:2023-11-30 21:17:41 25 4
gpt4 key购买 nike

假设我有一个这样的 reducer :

export const fetchStuff = (state, action) => {
const s = state || someDefaultState
switch (action.type) {
case FETCH_STUFF:
return {...s, isFetching: true}
case SET_STUFF:
return {...s, isFetching: false, stuff: action.values}
default:
return s
}
}

在这种情况下,如果 actions.values 具有 null 的对象,它们将很难在我的组件中处理,因为我必须手动确保组件没有传递 null prop,然后还必须手动处理组件中某处的 null 字段。

const component = ({ prop }) => {
return {
<div>
<span>{prop.testnull ? '' : prop.testnull}</span>
<div
}
}

const mapStateToProps = (state) => {
const p = prop || someDefaultProp
return {
prop: state.prop
}
}

在这个例子中看起来很容易,但我发现管理更大的组件/组件集很痛苦。这样做的惯用方法是什么?我是否必须硬着头皮在组件和 mapStateToProps 中进行管理?还是有更好的方法在 reducer 中管理它?

编辑:

我应该澄清一下,我不是要处理 statenull 的情况,而是要处理获取状态时的情况, 一些属性如果状态设置为空

最佳答案

我们已经使用了一些类似的解决方案一段时间,并发现这是在我们的 reducer 中处理此用例的好方法。 Lodash 的 _.get 是一个很好的解决方案,可以为你的 reducer 中的多级获取提供默认值:

https://lodash.com/docs/4.17.4#get

_.get(object, path, [defaultValue])

  • object (Object): The object to query.
  • path (Array|string): The path of the property to get.
  • [defaultValue] (*): The value returned for undefined resolved values.

例如:

const testValue = get(action, 'values.test', {});

关于javascript/redux : how to avoid null when fetching state?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45508264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com