【发布时间】:2020-08-20 12:30:03
【问题描述】:
我正在尝试使用 JSON Placeholder REST API 使用 redux 作为状态管理 API 创建一个 React 组件。我能够看到在 redux 记录器中调度了动作,但是当我试图通过组件的属性访问更改的状态时,我在浏览器控制台窗口中得到“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
});
}
);
}
主组件:
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>
);
}
}
【问题讨论】:
标签: reactjs react-redux