未定义调度/未在操作中定义存储

时间:2018-11-29 18:14:18

标签: reactjs redux react-redux

在我的响应redux应用程序中的动作中,当我尝试分派动作时,得到的分派未定义no-undef错误消息。当我将dispatch更改为store.dispatch时,我将得到与store相同的消息。我的商店的配置如下:

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION__COMPOSE|| compose;
const store = createStore(
  rootReducer,composeEnhancers(applyMiddleware(thunk))
)

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <Route  component={App}/>
    </Router>
  </Provider>,
  document.getElementById('root')
);
register();

我的动作已这样设置:

export function login(email,password){
  const url = 'http://localhost:3000/login';
  let data= JSON.stringify({
    email: email,
    password: password
  });
  const headers = {
    'Content-Type':'application/json',
    'Accept': 'application/json'
  };


  return function(dispatch){
    return fetch(url,{
      method: 'POST',
      headers:headers,
      body: data
    })
    .then(res => {
      if (res.status === 401) {
            alert("login failed");
          } else {
            return res.json();
          }
    })
  }
  .then(json=>{
    localStorage.setItem('token',json.token)
    dispatch({type:SET_USER, user:json.user})
  })
}

和我的减速器设置:

import {combineReducers} from 'redux'

 function userReducer(state=null,action){
  switch(action.type){
    case 'SET_USER':
      return action.user
    default:
      return state
  }
}
const rootReducer = combineReducers({
  user:userReducer
})
export default rootReducer

我已经阅读了文档,但没有找到答案,并且此设置与我构建的上一个应用程序非常相似。

1 个答案:

答案 0 :(得分:0)

尝试一下

export function login(email,password){
  const url = 'http://localhost:3000/login';
  let data= JSON.stringify({
    email: email,
    password: password
  });
  const headers = {
    'Content-Type':'application/json',
    'Accept': 'application/json'
  };


  return function(dispatch){
    return fetch(url,{
      method: 'POST',
      headers:headers,
      body: data
    })
    .then(res => {
      if (res.status === 401) {
            alert("login failed");
          } else {
            return res.json();
          }
    })
    .then(json=>{
      localStorage.setItem('token',json.token)
      dispatch({type:SET_USER, user:json.user})
    })
  }

}