如何在没有 运行 的情况下使用从 Redux 返回的嵌套数据结构到诸如 'cannot access property x of undefined' 之类的错误中?

How to I consume nested data structures returned from Redux without running into errors such as 'cannot access property x of undefined'?

我正在尝试使用 Redux 选择器从 Redux 存储返回的嵌套数据结构中提取特定数据。

const getContactPhone = state => (state.home.data.blocks[1].contactPhone);

我从 API 获取这些数据,并在我的 Next.js 站点使用 getInitialProps 加载时将其存储在商店中。商店数据似乎出现又消失——也许这与 Next.js 和 next-redux-wrapper 处理商店创建的方式有关。例如,无论如何我总是收到 'cannot read contactPhone of undefined' 错误。

显然我可以把支票放在

const getContactPhone = state => (state && state.home && state.home.data 
 && state.home.data.blocks && state.home.data.blocks[1] ? state.home.data.blocks[1].contactPhone : '');

但这看起来很尴尬和丑陋。有没有更好的方法来处理这个问题?有什么图书馆可以帮助我吗?

感谢您提供有关前进道路的任何线索!

Ramda 有一个 path 函数。您将路径作为字符串数组传递给 属性。如果 属性 存在,则返回其值;否则 returns undefined.

console.log(R.path(['a', 'b', 'c', 0], { a: { b: { c: [1, 2] } } })); // 1
console.log(R.path(['a', 'b', 'c', 0], {})); // undefined
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>