如何在 React 中渲染对象的属性? [英] How to render properties of objects in React?

查看:61
本文介绍了如何在 React 中渲染对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该在哪里处理这个组件没有加载所需的state的问题?

Where exactly should I deal with the problem of this component not loading with the desired state?

我的渲染方法导致以下错误...

My render method causes the following error...

Uncaught TypeError: Cannot read property 'email' of undefined

...即使 JSON.stringify 行告诉我 email 属性确实(最终)存在.

...even though the JSON.stringify line shows me that the email property does (eventually) exist.

mapStateToProps 中的 console.log 确认状态首先加载,没有任何 user 属性(从而导致错误).>

看我在构造函数方法中解决这个问题的天真尝试.它不起作用.

The console.log down in mapStateToProps confirms that state loads first without the any user property (thus causing the error).

处理这种情况的正确方法是什么?渲染方法中的一些条件?也尝试过,但仍然没有运气.

Behold my naive attempt to resolve this in my constructor method. It's not working.

What is the right way to deal with this situation? Some conditional inside the render method? Tried that too but still no luck.

);}}函数 mapStateToProps(state) {console.log('state',state);返回 { 用户:state.auth.user }}导出默认连接(mapStateToProps,动作)(功能);

import React, {Component, PropTypes} from 'react'; import {connect} from 'react-redux'; import * as actions from '../actions'; class Feature extends Component { constructor(props){ super(props); this.state = { 'auth': { 'user':{ email:'', id:'' } } } } componentWillMount() { this.props.fetchMessage(); // puts the user object into state } render() { return ( <div className="feature"> Here is your feature {JSON.stringify(this.props.user , null, 2)} {this.props.user.email} </div> ); } } function mapStateToProps(state) { console.log('state',state); return { user: state.auth.user } } export default connect(mapStateToProps, actions)(Feature);

///////////动作/////////

/////////// action /////////

export function fetchMessage(){

    return function(dispatch){
        axios
            .get(ROOT_URL, {
                headers: {
                    authorization: localStorage.getItem('token')
                }
            })
            .then((response) => {
                dispatch({
                    type: FETCH_MESSAGE,
                    payload: response.data.user
                })
            })
    }

}

/////////////////减速器////////////

///////////////// reducer /////////////

var authReducer = (state={}, action) => {
    console.log('action.payload',action.payload);

    switch(action.type){
        case AUTH_USER: return      {...state, error: '', authenticated: true};
        case UNAUTH_USER: return    {...state, error: '', authenticated: false};
        case AUTH_ERROR: return     {...state, error: action.payload};
        case FETCH_MESSAGE: return  {...state, user: {
                                                        email: action.payload.email,
                                                        id: action.payload._id
                                                    }};
        default: return state;
    };
};

推荐答案

Redux 使用一个名为 store全局状态,它位于您的组件之外.

Redux uses a global state called store that lives outside your component.

在您的 constructor 中,您有一个 this.state = {...} 语句.这是一个仅对 Feature 组件可用的本地状态.

Inside your constructor you have a this.state = {...} statement. This is a local state that is only available to the Feature component.

connect from react-redux 基本上将 store 中的信息连接到您的组件 props 因此称为 <代码>mapStateToProps.

connect from react-redux basically connects the info inside the store to your component props hence called mapStateToProps.

将您的 mapStateToProps 编辑为类似...

Edit your mapStateToProps to something like...

function mapStateToProps(state) {
   const { auth: { user = {} } = {}} = state;
   return {
      user
   }
}

它所做的是尝试从商店中提取 user 属性,如果它还不存在,则将其设置为空对象.您的错误是由于您的 mapStateToProps 访问了尚不存在的用户属性.您可能希望将默认值设置为您的 initialState 以避免此问题.

What it does is try to extract the user property from the store and if it doesn't exist yet, set it to empty object. Your error is due to your mapStateToProps accessing the user property that doesn't exist yet. You might want to set a default value as your initialState to avoid this issue.

这篇关于如何在 React 中渲染对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆