axios 如何使用react redux来显示来自option select中API的数据?

7hiiyaii  于 2022-12-18  发布在  iOS
关注(0)|答案(2)|浏览(142)

在请求一个locale API之后,我必须获取响应数据并将其放入select中。为了确定请求是否正确,我创建了console.log(DATA STATE)并得到以下返回:

DATA STATE 
{data: Array(27), status: 200, statusText: "OK", headers: AxiosHeaders, config: Object…}
data: Array(27)
0: Object
id: 12
sigla: "AC"
nome: "Acre"
regiao: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
12: Object
13: Object
14: Object
15: Object
16: Object
17: Object
18: Object
19: Object
20: Object
21: Object
22: Object
23: Object
24: Object
25: Object
26: Object
status: 200
statusText: "OK"
headers: AxiosHeaders
config: Object
request: XMLHttpRequest

我尝试在SelectState组件中Map状态选择(states-〉index.js),但是没有返回任何信息。(data.nome)中的值(states-〉index.js)州的城市出现在SelectCity组件的select中(city-〉index.js),选择城市后,在InformationCity组件(informationCity-〉index.js)中以微区、中区的形式显示所选城市的信息。

import React, { useState, useEffect } from "react";
import { FormControl, InputLabel, MenuItem, Select } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { getStates } from "../states/statesSlice";

export const SelectState = () => {
  const dispatch = useDispatch();
  const states = useSelector((state) => state.states.dataState);
  const [stateSelected, setStateSelected] = useState("");

  useEffect(() => {
    dispatch(getStates());
  }, [dispatch]);

  const handleChange = (event) => {
    dispatch(setStateSelected(event.target.value));
  };

  return (
    <FormControl sx={{ m: 1, minWidth: 120 }} size="small">
      <InputLabel id="demo-select-small">State</InputLabel>
      <Select
        labelId="demo-select-small"
        id="demo-select-small"
        value={stateSelected}
        label="estados"
        onChange={handleChange}
      >
        <MenuItem disabled>Select a state</MenuItem>
        {states.length > 0 &&
          states.map((item) => (
            <MenuItem key={item.id} value={item.sigla}>
              {item.nome}
            </MenuItem>
          ))}
      </Select>
    </FormControl>
  );
};

Follow the code link in codesandbox
我是Redux的新手,我已经在index.js中创建了store.js、slices和provider。

mccptt67

mccptt671#

您可以通过以下方式添加setState函数:

export const setState = createAsyncThunk(
  "state/setState",
  async (selectedState, { rejectWithValue }) => {
    try {
      return selectedState;
    } catch (err) {
      return rejectWithValue([], err);
    }
  }
);

reducers列表中,

builder.addCase(setState.fulfilled, (state, action) => {
      state.selectedState = action.payload;
    });

然后调用setState函数设置选中状态:

dispatch(setState(e.target.value));


同样的方法也适用于getCities
代码有点长,但我想这可能对将来代码库的维护和扩展更好。
工作演示在这里:https://codesandbox.io/s/createasyncthunk-createslice-redux-forked-9qwene?file=/src/features/states/statesSlice.js

bqf10yzr

bqf10yzr2#

这里有两件事要做:首先,states/index.js中的分派被破坏了-dispatch接受一个普通对象,或者通过action creator创建,或者是一个简单的文本。
所以这个...

const handleChange = (event) => {
    dispatch(setStateSelected(event.target.value));
};

应该是这样的

const handleChange = (event) => {
    dispatch({ action:"state/setState", payload: event.target.value });
};

此外,在thunk中,您会得到一个错误,因为您试图将整个响应(头和所有)放入存储区。

return response // represents the whole response with metadata


你只是想

return response.data // the array of states

相关问题