Redux工具包数组定义

8ljdwjyq  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(168)

我正在学习redux-toolkid,我尝试通过在Redux-toolkid中定义数组来拉取数据,但是当我定义如下时,我得到了图片中的错误。描述const newList = { id:“1”,文本:“抄送”,};不幸的是,尽管我做了很多尝试,但还是无法将其定义为数组。

`import React from 'react';
import {View, Text, Button, FlatList} from 'react-native';
import {Provider, useDispatch, useSelector} from 'react-redux';
import {configureStore, createSlice} from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: [],
  reducers: {
    increment: (state, action) => {
      const newList = {
        id: "1",
        text: "cc",
    };
      state.push( newList);
    },
    deincrement: state => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

const store = configureStore({
  reducer: {
    counter: counterSlice.reducer,
  },
});

export const {increment, deincrement, incrementByAmount} = counterSlice.actions;

export default () => {
  return (
    <Provider store={store}>
      <View style={{flex: 1}}>
        <First />
        <Second />
      </View>
    </Provider>
  );
};

const First = () => {
  const counter = useSelector(state => state.counter);
  const dispatch = useDispatch();

  return (
    <View style={{flex: 1, backgroundColor: 'yellow'}}>
      <Text style={{color: 'red', fontSize: 40}}>First : {counter}</Text>

      <Button title={'-'} onPress={() => dispatch(deincrement())} />
    </View>
  );
};

const Second = () => {
  const counter = useSelector(state => state.counter);
  console.log(counter);
  const dispatch = useDispatch();

  return (
    <View style={{flex: 1}}>
      <Text style={{fontSize: 40}}>Second : {counter}</Text>
      <Button title={'+'} onPress={() => dispatch(increment())} />
    </View>
  );
};

const newList = {
        id: "1",
        text: "cc",
    };`

你可以在这里找到照片

vh0rcniy

vh0rcniy1#

您 * 已经 * 将其定义为array,这就是问题所在!
这里counter的值是一个array

const counter = useSelector(state => state.counter);

因此,您将在以下行中得到错误:
x一个一个一个一个x一个一个二个x
你不能在文本中使用{counter},因为它不是文本,而是objectarray
实际上,如果arraystringnumber等的数组,则可以将其作为子元素。但是,当React尝试呈现array的第一个元素时,它会发现object{ id: "1", text: "cc" }),并且无法呈现该元素。
如果您只是玩玩,想看看state的值,那么试试这个:

<Text style={{color: 'red', fontSize: 40}}>First : {JSON.stringify(counter)}</Text>

请注意,只有您的increment操作才有效。调度deincrementincrementByAmount将在Reducer中导致致命错误,因为您的statearray,并且state.value未定义。

相关问题