【问题标题】:Displaying contents of an array using React and Redux使用 React 和 Redux 显示数组的内容
【发布时间】:2020-05-21 18:19:52
【问题描述】:

我是 React 的新手,甚至是 Redux 的新手。我要做的就是将数组的内容输出到网页。我想维护 Redux 结构(单向数据流,reducers)。当我单击 Generate a New Array 按钮时,reducer 会生成一个数组并保存为状态。在我尝试使用map 输出数组时,我看到错误告诉我myarray.map is not a function。考虑到我从状态中拉出数组,我有点困惑,它应该被填充。

初始状态

const initialState = {
  array: [],
  algo: null,
  size: 30,
}

减速器

const arrayReducer = (state,action) => {
  if (action.type === GENERATE_NEW_ARRAY){
    let arr = [];
    let size = state.size;
    let limit = size*3;

    for(let i=0;i<size;++i){
      let num = Math.floor((Math.Random() * limit) + 1);
      arr.push(num);
    }

    return { array: arr };
  }
  return state || { array: [] };
};

const rootReducer = combineReducers({
  array: arrayReducer,
  algo: algoReducer,
  size: sizeReducer,
});

选择器

const getSize = state => state.size;

反应组件

function GenerateNewArray({ value, generateNewArray }){
  return(
    <div>
      <button onClick={() => generateNewArray(value)}>
        Generate a New Array
      </button>
    </div>
  )
}
const GenerateNewArrayConnected = connect(
  state => ({
    size: getSize(state)
  }),
  dispatch => ({
    generateNewArray: size => dispatch(generateNewArray(size))
  })
)(GenerateNewArray);

我希望数组出现在“生成新数组”按钮下方,但我希望它作为一个单独的实体(如果可能),因为它们最终将是两个单独的组件。显示数组的最佳方法是什么?

【问题讨论】:

  • 能把myarray.map的代码加进去吗?

标签: reactjs redux react-redux


【解决方案1】:

假设为你的rootReducer定义了initialState,你只需要从arrayReducer而不是{array: arr}返回数组

const arrayReducer = (state,action) => {
  if (action.type === GENERATE_NEW_ARRAY){
    let arr = [];
    let size = state.size;
    let limit = size*3;

    for(let i=0;i<size;++i){
      let num = Math.floor((Math.Random() * limit) + 1);
      arr.push(num);
    }

    return arr;
  }
  return state;
};

【讨论】:

  • 谢谢!我仍然看不到数组,但这使错误消失了。我会多玩一点,看看能不能得到一些输出。
  • 很高兴能帮上忙
猜你喜欢
  • 2017-06-13
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多