在react组件中“使用”后,来自redux动作的空数组

时间:2019-02-03 13:36:12

标签: javascript reactjs redux react-redux

React组件调用redux动作,该动作从后端服务器获取响应(可用协作的二维数组),并将数据分发到reducer并将其设置为state。

减速器:

case GET_COLLABS:
      return {
        ...state,
        collabs: action.payload,
        loading: false
      };

操作:

export const getCollabs = () => dispatch => {
  dispatch(setLoadingState());
  axios
    .get("/api/collab")
    .then(res => {
      console.log(res.data);
      dispatch({
        type: GET_COLLABS,
        payload: res.data
      })   
    }
    )
    .catch(err =>
      dispatch({
        type: GET_COLLABS,
        payload: null
      })
    );
};

组件:

componentWillMount(){
    this.props.getCollabs();
    this.props.getCurrentProfile(); 
  }

  componentWillReceiveProps() {
    this.setState({
      collabs: this.props.collab.collabs
    })
  }

    render() {     
      const { collabs, loading } = this.props.collab;
      const { profile } = this.props.profile;
      let collabsContent;   

      if (collabs === null || loading || profile === null) {       
        collabsContent = <Spinner />;
      } else {
        if (collabs.length > 0 && profile.interests.length > 0) {
          collabsContent = collabs.map((collab, index) => <CollabSection key={index} collabs={collab} head={profile.interests[index]} />);
        } else {
          collabsContent = <Spinner />;
        }
      }
return(doesnt matter)

  CollabFeed.propTypes = {
    collab: PropTypes.object.isRequired,
    getCollabs: PropTypes.func.isRequired,
    getCurrentProfile: PropTypes.func.isRequired
  };

  const mapStateToProps = state => ({
    collab: state.collab,
    profile: state.profile
  });

  export default connect(
    mapStateToProps,
    { getCollabs, getCurrentProfile }
  )(CollabFeed);

当我注释掉

collabsContent = collabs.map((collab, index) => <CollabSection key={index} collabs={collab} head={profile.interests[index]} />);
从组件

可以正常工作(显然它不会在浏览器中显示任何内容,但是redux状态是预期的) https://imgur.com/a/JyjLxbR 但是当我离开它时,一切都呈现为好像已设置数据一样,但是redux存储中有空数组... https://imgur.com/a/hlPaY2x

从操作中获得console.log(res.data)时,它看起来与state.collab相同

0 个答案:

没有答案