// 这是reducer
export const requestUserInfo = (state = {}, action) => {
switch(action.type) {
case 'HEADER_RECEIVE_USERINFO':
console.log(action.data)// 有值
return Object.assign({}, state, action.data)
break
default:
return state
}
}
// 这是action
function receiveUserInfo (data) {
return {
type: 'HEADER_RECEIVE_USERINFO',
data
}
}
export function requestUserInfo () {
return dispatch => {
return axios.post('/user/getScores', qs.stringify({
token: token,
uid: uid
}))
.then(res => {
if(res.data.status !== 200) {
message.error(res.data.message)
return state
}
return { ...res.data.attachment}
})
.then(data => {
dispatch(receiveUserInfo(data))
})
}
}
action 和 reducer 都能正常执行,我在router中监听了store,但是store一直都没有变过。是我哪里写错了吗?
快来人救救我,卡在这个问题一整天了,完全不知道哪里出的问题
又过了一天,今天看了下文档,还是没能定位到bug出在哪个地方。我改了下reducer,让不经过action的异步请求处理,直接返回一个对象,下面是代码。
const init = {
uname: '张三',
point: 10000,
notice: 10
}
export const requestUserInfo = (state = {}, action) => {
switch(action.type) {
// 组件中直接使用的dispatch({type: 'HEADER_RECEIVE_USERINFO'})来触发
case 'HEADER_RECEIVE_USERINFO':
return {
...init
}
break
default:
return state
}
}
之后设置了connect和mapStateToProps方法,如下
function mapStateToProps (state, ownProps) {
// 这里的state打印出来的并没有我返回的数据
console.log(state, 'state')
return {
uname: state.uname,
point: state.point,
notice: state.notice
}
}
export default connect(mapStateToProps)(Header)
我在didMount里面打印了当前的props,除了得到uname,point,notice这几个全是undefined的值之外,
就只有一个dispatch方法,上面也没有store
componentDidMount() {
const { dispatch } = this.props
if (!token && !uid) return
console.log(this.props, 'props')
dispatch({type: 'HEADER_RECEIVE_USERINFO'})
}
有人能告诉我bug出在哪里吗?现在连个错都没有报,我想解决却不知道问题出在哪里,真是愁死了。
想了下,还是把入口route的文件也发出来吧,下面是入口文件的相应代码
const store = createStore(
combineReducers({
...reducer,
routing: routerReducer // 用的react-router-redux库
}),
applyMiddleware(thunk)
)
// store.subscribe(() => { //监听state变化
// console.log(store.getState(), 'store.getState()')
// });
const history = syncHistoryWithStore(hashHistory, store)
render (
<Provider store={store}>
{ routes }
</Provider>
, document.getElementById('app'))
你的写法有问题:
reducer: