【发布时间】:2017-11-22 11:30:23
【问题描述】:
我在这里遇到了问题,我已经做 redux 大约 2 周了。
我正在尝试创建一个加载程序,因此我正在尝试获取 isFetching 状态。使用 thunk,我正在执行 ajax 获取,并调度加载状态。
调用了调度,因为我可以在控制台中看到。
在组件挂载之前,它假设调用 FETCH_PROFILE,并且 isFetching 设置为 true,但是当我在 console.log(this.props.profile.isFetching) 时,它返回 false。
与 FETCH_PROFILE_SUCCESS 相同,它不会更新 this.props.profile。 (或者因为它没有重新渲染......所以我看不到它)
我已经在这个简单的事情上工作了几个小时,但我不知道为什么它没有更新......我确定我在某个地方犯了一些错误,但不知道是什么。
export const FETCH_PROFILE = 'FETCH_PROFILE';
export const FETCH_PROFILE_SUCCESS = 'FETCH_PROFILE_SUCCESS';
export const FETCH_PROFILE_FAIL = 'FETCH_PROFILE_FAIL';
export function getUserProfile() {
return (dispatch) => {
dispatch(getUserProfileStart());
const config2 = {
method: 'GET',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
credentials: 'include',
body: ``,
};
fetch('http://api.example.com/profile/',config2)
.then((resp) => resp.json())
.then(function(data) {
dispatch(getUserProfileSuccess(data));
return 0;
}).catch(function(error){
return dispatch({type: FETCH_PROFILE_FAIL});
})
}
}
function getUserProfileSuccess(data) {
return {
type: FETCH_PROFILE_SUCCESS,
isFetching: false,
payload: data
}
}
function getUserProfileStart() {
return {
type: FETCH_PROFILE,
isFetching: true
}
}
我的减速器
import {
FETCH_PROFILE,
FETCH_PROFILE_SUCCESS,
FETCH_PROFILE_FAIL
} from '../actions/profile';
export default function userProfile(state={isFetching: false}, action) {
switch(action.type) {
case FETCH_PROFILE:
return {...state, isFetching: true}
case FETCH_PROFILE_SUCCESS:
return {...state, isFetching: false, data: action.payload}
case FETCH_PROFILE_FAIL:
return { ...state, isFetching: false };
default:
return state
}
}
我的组件。
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import {connect } from 'react-redux';
import * as profileActions from '../../actions/profile';
import {bindActionCreators} from 'redux';
class ProfilePage extends React.Component {
constructor(props) {
super(props);
this.getUserProfile = this.getUserProfile.bind(this);
}
componentWillMount() {
this.props.actions.getUserProfile();
}
render() {
console.log('Checking isFetching State', this.props.profile.isFetching);
return (
<div>
some text here.
</div>
);
}
}
function mapStateToProps(state) {
console.log('Mapping Stat', state.profile);
return {
profile: state.userProfile
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(profileActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(s)(ProfilePage));
我的联合减速机...
import userProfile from './profile';
//some other imports...
export default combineReducers({
userProfile,
//other reducers that works...
});
【问题讨论】:
标签: reactjs react-redux