简体   繁体   English

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

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

I have a situation where i can successfully dispatch my states with reducers and i can render it in my component我有一种情况,我可以使用减速器成功调度我的状态,并且我可以在我的组件中渲染它

Here the relevant code这里是相关代码

in my action/index.js在我的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);
        });
    }
}

my reducers/index.js我的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;
  }
};

in my component component/Leagues.js在我的组件component/Leagues.js

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


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

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

const mapDispatchToProps = {
  getList: fetchLeaguesList
};

I have reproduced the demo here => https://codesandbox.io/s/select-demo-71u7h ?我在这里复制了演示 => https://codesandbox.io/s/select-demo-71u7h

I can render my leaguesList states in my component doing the map, but why when我可以在执行 map 的组件中渲染我的leaguesList状态,但是为什么

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

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

returns an empty array?返回一个空数组?

See the image看图片在此处输入图像描述

You're setting useState's init value wrong:您将 useState 的初始值设置错误:

 const [itemsLeagues] = useState(leaguesList);

instead of代替

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

The return value of useState isn't the value itself, but the array of value and mutator: useState 的返回值不是 value 本身,而是 value 和 mutator 的数组:

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

So if you were trying to destructure the wrapping array you passed to useState(), you should use it like this (though you don't need it):所以如果你试图解构你传递给 useState() 的包装数组,你应该像这样使用它(尽管你不需要它):

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

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

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