如何解决尝试将React组件与Redux连接时获取'this.props.user'是未定义的
我正在尝试使用JSON占位符REST API创建一个React组件,并使用redux作为状态管理API。我能够看到动作在redux logger中调度,但是以某种方式,当我尝试通过组件的属性访问更改的状态时,在浏览器控制台窗口中未定义'this.props.user'。请在下面找到我的代码:
减速器:
import {FETCH_DATA} from '../Actions/actionTypes';
const initialState={
userlist:[]
}
function jphReducer(state=initialState,action){
switch(action.type){
case FETCH_DATA:
state={
...state,userlist:action.payload
}
break;
default :
state;
}
return state;
}
export default jphReducer;
动作:
import axios from 'axios';
import {FETCH_DATA} from '../Actions/actionTypes';
export const getjphData = () => async dispatch => {
await axios.get("https://jsonplaceholder.typicode.com/users").then(
response => {
dispatch({
type:FETCH_DATA,payload:response.data
});
},reason => {
dispatch({
type:FETCH_DATA,payload:reason
});
}
);
}
MainComponent:
import React,{Component} from 'react';
import {getjphData} from '../app/Actions/jphAction';
import { connect } from 'react-redux';
import jphReducer from '../app/Reducers/jphReducer';
import propTypes from "prop-types";
import { FETCH_DATA } from './Actions/actionTypes';
class MainComponent extends Component{
constructor(props){
super(props);
}
componentDidMount(){
this.props.getData();
}
render(){
return(
<div>
<table>
<thead>
<th>
<td>ID</td>
<td>name</td>
<td>username</td>
<td>Email</td>
</th>
</thead>
<tbody>
{
this.props.users.map((user) =>
<tr>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
</tr>
)
}
</tbody>
</table>
</div>
);
}
}
const mapDispatchToProps = dispatch => ({
getData : dispatch(getjphData())
});
const mapStateToProps = state => ({
users: state.userlist
});
export default connect(mapStateToProps,mapDispatchToProps)(MainComponent);
根组件:
import React,{Component} from 'react';
import {Provider} from 'react-redux';
import {jphStore} from './jphStore';
import MainComponent from './MainComponent';
import { connect } from 'react-redux';
export default class RootComponent extends Component{
constructor(props){
super(props);
}
render(){
return(
<Provider store={jphStore}>
<MainComponent/>
</Provider>
);
}
}
解决方法
您的users.map
尝试立即运行,甚至在完成获取用户请求之前也是如此,以确保在尝试映射props.users
之前已定义this.props.users && this.props.users.map...
,在此之前添加一个条件{ {1}}
您的tbody
应该看起来像这样
<tbody>
{
this.props.users && this.props.users.map((user) =>
<tr>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
</tr>
)
}
</tbody>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。