使用react redux

时间:2016-07-28 09:54:58

标签: javascript reactjs redux react-redux

我在 React Redux 项目中遇到api调用问题。这是项目的代码片段。

poiAction.js

export function poiSuccess(pois) {
  // The log detail is below
  console.log("POI: ", pois);
  return {
      pois,
      type: POI_FETCH_SUCCESS
  };
}
export function poiFetch(pois) {
  return {
    pois,
    type: POI_FETCH_ATTEMPT
  };
}

export function fetchPoi(token) {
  return dispatch =>
    axios({
      method: 'get',
      url: 'http://localhost:9090/poi',
      headers: {
        'x-access-token': token
      },
    })
    .then((pois) =>{
      // let poi = pois.data[0];
      // console.log("POIS: ", pois.data[0]);
      dispatch(poiSuccess(pois));
    })
    .catch((error) => {
      throw(error);
    })
}

控制台日志输出:

console.log("POI:", pois)

poiReducer.js

export default function poi(state = [], action){
  switch(action.type){
    case POI_FETCH_ATTEMPT:
    return state;
    case POI_FETCH_FAILED:
    return state;
    case POI_FETCH_SUCCESS:
    // The console log output is same as poiAction
    console.log("Reducer: ", action.pois);
    return [action.pois, ...state];
    break;

    default:
      return state;
  }
}

控制台日志输出与poiAction

相同

Root Reducer

const rootReducer = combineReducers({
  LoginReducer,
  PoiReducer
});

显示api调用列表的组件:

Dashboard.js

class Dashboard extends Component {
  constructor(props) {
    super(props);

    this.state = {
      poi: '',
      token: null
    };
  }
  componentWillMount() {
    let token = sessionStorage.getItem("token");
    this.setState({token});
    this.props.actions.fetchPoi(token);
  }
  render() {
    console.log("POIS: ", this.props.pois);
    return (
      <div>
        <h1>Dashboard</h1>

      </div>
    );
  }
}

Dashboard.propTypes = {
  pois: PropTypes.array.isRequired,
  actions: PropTypes.object.isRequired,

};

function mapStateToProps(state) {
  console.log("State: ", state);
  return {
    pois: state.poiReducer
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(poiAction, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);

此处this.props.poisundefinedstate的{​​{1}}值为:

state value

我错过了什么?如何访问从api调用返回的列表?

由于

1 个答案:

答案 0 :(得分:1)

组合缩减器时,可以执行此操作

const rootReducer = combineReducers({
  LoginReducer,
  PoiReducer
});

表示

const rootReducer = combineReducers({
  LoginReducer : LoginReducer,
  PoiReducer : LoginReducer
});

这不是你想要的。

应该是

const rootReducer = combineReducers({
  loginReducer : LoginReducer,
  poiReducer : LoginReducer
});

另外,由于某些原因,你的root reducer里面有一个rootReducer,这有点奇怪。

所以访问poiReducer的方式是

function mapStateToProps(state) {
  console.log("State: ", state);
  return {
    pois: state.rootReducer.poiReducer
  };
}