我是React和Redux的新手,但仍然感到困惑。
我的目标是使用GET请求在HTML中呈现json数据。我使用react和redux来管理对象的状态,但我相信我的问题是数据不存在
这是代码:
Action.js:
import axios from 'axios';
export function fetchUsers(){
const request=axios.get('https://randomuser.me/api/');
return(dispatch)=>{
request.then(({data})=>{
dispatch({type:'FETCH_PROFILES',payload:data})
});
};
}
Component.js:
import React,{Component} from 'react';
import {connect} from 'react-redux';
import * as actions from '../actions';
class App extends Component {
ComponentWillMount() {
this.props.dispatch(onFetchUser());
}
render() {
const mappedUsers = this.props.users.map(user => <li>{user.email}</li>)
return <div>
<ul>{mappedUsers}</ul>
</div>
}
}
const mapStateToProps = (state) => {
return {
users: state.users.users
}
}
const mapDispatchToProps = (dispatch) => {
return {
onFetchUsers: () => dispatch(fetchUsers())
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
&#13;
CombineReducer.js:
import { combineReducers } from "redux"
import users from "./reducer-active-user"
export default combineReducers({
users ,
})
&#13;
Reducer.js:
const initialState = {
users: []
};
export default function reducer(state= initialState
, action) {
switch(action.type){
case 'FETCH_PROFILES':
return {
users: action.payload,
}
break;
}
return state;
}
&#13;
任何帮助都将不胜感激。
答案 0 :(得分:1)
您应该在axios .then
回调中回复调度,因为async
来电
import axios from 'axios';
export function fetchUsers(){
return function(dispatch) {
return axios.get('https://randomuser.me/api/')
.then(({data}) => {
dispatch({type:'FETCH_PROFILES',payload:data})
});
}
}
同样在您的组件中,您需要拨打onFetchUsers
class App extends Component {
componentWillMount() {
this.props.onFetchUsers()
}
render() {
const mappedUsers = this.props.users.map(user => <li>{user.email}</li>)
return (<div>
<ul>{mappedUsers}</ul>
</div>
)
}
}