所以我试图访问从后端服务器获取的值。数据正在Redux中进行更新,但是以某种方式我无法在render函数中访问它。
问题在于使用this.props.account
返回和对象。但是,当我尝试访问其中的任何内容时,例如this.props.account.role
,它表示未定义。但是之前由对象显示,应该说USER
这是我的代码
import React, {Component} from 'react';
import {Loading} from '../components/helpers/Loading.component';
import {Navbar} from '../components/navigation/Navigation.component';
import { connect } from 'react-redux';
import {fetchAccount} from '../actions/index.action';
export class Account extends Component {
componentDidMount() {
this.props.fetchAccount;
}
render() {
return (
<Loading isLoading={!this.props.account}>
<Navbar />
{console.log(this.props.account)}
</Loading>
);
}
}
const mapStateToProps = state => ({
account: state.account.account
});
const mapDispatchToProps = dispatch => ({
fetchAccount: dispatch(fetchAccount())
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Account)
这是我派遣的地方
export const fetchAccount = () => {
return dispatch => {
fetch(conf.http + '://' + conf.host + '/api/account', {
headers: {
"token": localStorage.getItem('token')
},
mode: 'cors',
method: 'GET'
}).then(data => (data.json())
.then(res => {
dispatch(receiveAccount(res))
}));
}
}
减速器
export const account = (state = [], action) => {
switch(action.type) {
case 'GET_ACCOUNT':
return {
...state,
account: action.payload
};
default:
return state;
}
}
和rootReducer
import { tickets } from './ticket.reducer';
import { account } from './account.reducer';
import {combineReducers} from 'redux';
export default combineReducers({
tickets,
account
});
答案 0 :(得分:1)
对于您在问题中所描述的内容,您尝试访问的是这样的对象数组:
accounts = [
{
name: 'Jimbo',
id: 1
role: 'player',
},
{
name: 'James',
id: 2,
role: 'employee'
},
]
您声明this.props.account.role
时。您正在尝试访问一个确实不存在的属性。
您可以尝试类似的操作,例如过滤数组(A),要访问的特定索引(B)或映射到数组(C)。
A: this.props.accounts.find(account => acount.role === 'player')
B: this.props.accounts[0].role
C: this.props.accounts.map(role => <li>{account.role}</li>)