如何避免在 Redux 的 mapStateToProps 中使用 && 逻辑运算符
How do I avoid using the && logical operator in mapStateToProps in Redux
当我在选择器中选择嵌套状态时,我不得不求助于使用 &&
逻辑运算符
const mapStateToProps = store => ({
image: store.auth.user && store.auth.user.photoURL;
});
不使用它会破坏应用程序,因为数据来自网络请求,需要一秒钟才能显示出来。
TypeError: Cannot read property 'photoURL' of null
是否有更好的方法来做到这一点,或者我应该在任何地方都使用 && 吗?看起来很乱,感觉很乱。
类似
const mapStateToProps = ({ auth }) => ({ image: auth.user ? auth.user.photoURL : null });
还有 ||
运算符 (/*...*/ image: (auth.user || {}).photoURL
),但如果它不那么骇人听闻的话,它就在旁观者的眼中。
如果您需要在多个地方执行此操作,您始终可以使用像 lodash 这样的库,或者只实现 _.get.
的一个版本
您可以使用 ?
运算符
image: store.auth.user ? store.auth.user.photoURL : undefined
或者您可以使用 ||
image: ( store.auth.user || {} ).photoURL
在 JS ?
中有 optional chaining 的提案
var street = user.address?.street
当我在选择器中选择嵌套状态时,我不得不求助于使用 &&
逻辑运算符
const mapStateToProps = store => ({
image: store.auth.user && store.auth.user.photoURL;
});
不使用它会破坏应用程序,因为数据来自网络请求,需要一秒钟才能显示出来。
TypeError: Cannot read property 'photoURL' of null
是否有更好的方法来做到这一点,或者我应该在任何地方都使用 && 吗?看起来很乱,感觉很乱。
类似
const mapStateToProps = ({ auth }) => ({ image: auth.user ? auth.user.photoURL : null });
还有 ||
运算符 (/*...*/ image: (auth.user || {}).photoURL
),但如果它不那么骇人听闻的话,它就在旁观者的眼中。
如果您需要在多个地方执行此操作,您始终可以使用像 lodash 这样的库,或者只实现 _.get.
的一个版本您可以使用 ?
运算符
image: store.auth.user ? store.auth.user.photoURL : undefined
或者您可以使用 ||
image: ( store.auth.user || {} ).photoURL
在 JS ?
var street = user.address?.street