繁体   English   中英

React Hooks useState Array 为空,在组件中呈现状态

[英]React Hooks useState Array empty with states rendered in the component

我有一种情况,我可以使用减速器成功调度我的状态,并且我可以在我的组件中渲染它

这里是相关代码

在我的action/index.js

export const receivedLeaguesList = json => ({
  type: RECEIVE_LEAGUES_LIST,
  json: json
});

export function fetchLeaguesList() {
  return function(dispatch) {
    dispatch(requestLeaguesList());
      return axios
        .get("https://www.api-football.com/demo/v2/leagues/")
        .then(res => {
          let leagues = res.data.api.leagues;
          dispatch(receivedLeaguesList(leagues));
        })
        .catch(e => {
          console.log(e);
        });
    }
}

我的reducers/index.js

import { REQUEST_LEAGUES_LIST, RECEIVE_LEAGUES_LIST } from "../actions";

const initialState = {
  leaguesList: [],
  isLeagueListLoading: false
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case REQUEST_LEAGUES_LIST:
      return { ...state, isLeagueListLoading: true };
    case RECEIVE_LEAGUES_LIST:
      return { ...state, leaguesList: action.json, isLeagueListLoading: false };
    default:
      return state;
  }
};

在我的组件component/Leagues.js

let Leagues = ({ leaguesList, loading, getList }) => {
  useEffect(() => {
    getList();
  }, [getList]);


  const [itemsLeagues] = useState([leaguesList]);

  console.log("league list", itemsLeagues);

const mapDispatchToProps = {
  getList: fetchLeaguesList
};

我在这里复制了演示 => https://codesandbox.io/s/select-demo-71u7h

我可以在执行 map 的组件中渲染我的leaguesList状态,但是为什么

  const [itemsLeagues] = useState([leaguesList]);

  console.log("league list", itemsLeagues); 

返回一个空数组?

看图片在此处输入图像描述

您将 useState 的初始值设置错误:

 const [itemsLeagues] = useState(leaguesList);

代替

 const [itemsLeagues] = useState([leaguesList]);

useState 的返回值不是 value 本身,而是 value 和 mutator 的数组:

const [value, setValue] = useState([42, 43])
// here's value equals [42, 43]

所以如果你试图解构你传递给 useState() 的包装数组,你应该像这样使用它(尽管你不需要它):

const [[itemsLeagues]] = useState([leaguesList]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM