简体   繁体   English

如何在React组件中访问嵌套的Redux状态?

[英]How to access nested Redux state in React components?

What's an efficient/elegant way to access nested data from branches of the state that are only available part of the time? 从状态的分支访问嵌套数据的有效/优雅方法是什么?这些数据仅在部分时间可用?

I'm new to React and this problem keeps coming up. 我是React的新手,这个问题不断涌现。 I have an ok grasp on Redux and using middleware like Thunk & Saga for the API stuff, but I still don't understand the proper way to write components so that they're not trying to grab non-existent state. 我对Redux的掌握很好,并且使用像Thunk和Saga这样的中间件来获取API的东西,但是我仍然不理解编写组件的正确方法,这样他们就不会试图抓住不存在的状态。

For example, when loading a user's profile photo into a header after the user signs in, the URL will be in the redux store as state.user.userData.photos.primary ...if I try to access that location when the user hasn't signed in, userData is still undefined and React will throw an error. 例如,在用户登录后将用户的个人资料照片加载到标题中时,该URL将作为state.user.userData.photos.primary在redux存储中...如果我尝试在用户登录时访问该位置登录后,userData仍未定义,React将抛出错误。 So my solution has been to write assignments like: 所以我的解决方案就是编写如下的作业:

let profilePhoto = props.user.userData ? props.user.userData.photos.primary : '';

... which seems cumbersome and inefficient, especially since it requires mapping the entire userData object in mapStateToProps only for the sake of accessing a tiny chunk of data. ...这看起来既麻烦又低效,特别是因为它只需要为了访问一小块数据而映射mapStateToProps中的整个userData对象。

I wish I could target it earlier. 我希望我能早点瞄准它。 For example, in mapStateToProps: 例如,在mapStateToProps中:

profilePhoto : state.user.userData.photos.primary || '';

...but that results in "can't access 'photos' of undefined". ...但这会导致“无法访问未定义的照片”。 So what's an efficient/elegant way to access nested data from branches of the state that are only available part of the time? 那么从状态的分支访问嵌套数据的有效/优雅方法是什么呢?这些数据只在部分时间可用?

In your mapStateToProps access your state like this: 在你的mapStateToProps中访问你的状态如下:

profilePhoto : state.user.userData ? state.user.userData.photos.primary : ''

and then use profilePhoto as props. 然后使用profilePhoto作为道具。 This will not throw an error of undefined. 这不会抛出未定义的错误。

In my current application I initialize the redux state with all the data tree that I will use; 在我当前的应用程序中,我使用我将使用的所有数据树初始化redux状态; so that I will unlikely end up with undefined s. 所以我不太可能最终得到undefined s。

So a solution would be: 所以解决方案是:

const initialState = {
    userData: {
        photos: {
            primary: ""
        }
    }
}

This might look ugly in the first glance but it helps me keep track of what my data will look like, and can be simplified by defining parts of the object individually. 这看起来可能在第一眼看上去很丑,但它可以帮助我跟踪我的数据的样子,并且可以通过单独定义对象的部分来简化。

An alternative could be keeping a flag in the redux state like isUserPrimaryPhotoDefined which you would set to true when you are setting the primary variable; 另一种方法是将一个标志保持在redux状态,如isUserPrimaryPhotoDefined ,当你设置主变量时,你将设置为true; so you can use the flag in the ternary. 所以你可以使用三元组中的旗帜。 However that might not guarantee getting rid of the possible errors completely. 但是,这可能无法保证完全消除可能的错误。

With ES6 Destructuring Assignment , you can access nested keys from props in a cleaner way. 使用ES6 Destructuring Assignment ,您可以更清晰地从props访问嵌套键。

const { user: { userData: { photos: { primary = ''} = {}} = {}} = {}} = props;
console.log(primary); // prints primary value or '' if not defined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM