gpt4 book ai didi

javascript - 如何在 Redux 中使用 reducer 进行多个操作?

转载 作者:行者123 更新时间:2023-11-30 19:26:33 25 4
gpt4 key购买 nike

我是 Redux 的新手,我正在尝试将 React 与 Redux 集成。我想要的是将我所有的 Action 都放在一个 reducer 中。实际上我的 reducer 看起来像这样:

import {GET_ALL_CONNECTIONS, DELETE_CONNECTION, POST_CONNECTION} from '../actions';

const initialState = {

}

export default (state = initialState, { type, payload }) => {
switch (type) {

case GET_ALL_CONNECTIONS:
return payload

case POST_CONNECTION:
return {...state, ...payload}

case DELETE_CONNECTION:
return {...state, ...payload}

default:
return state
}
}

问题是当我调用对应于 GET_ALL_CONNECTIONS 类型的操作时:

export const getAllConnections = () => {
return async (dispatch) =>{
const response = await Conexiones.get('/db/myConnections');
dispatch({type: GET_ALL_CONNECTIONS, payload: response.data});
}
}

当我在 React 组件中调用此函数时,应该从 API 获取多个连接,并将 API 调用结果的对象数组保存在状态中。问题是当我想在状态中保存连接数组时,稍后映射该状态并生成 optionsselect 元素内的每个连接。当我渲染组件时,它会抛出下一个错误:

TypeError: this.props.conexiones.map is not a function

我组合所有 reducer 的文件如下所示:

import {combineReducers} from 'redux';
import {reducer as formReducer } from 'redux-form';

import postUser from './postUser';
import postConnection from './postConnection';
import getAllConnections from './getAllConnections';
import ConnectionsReducer from './ConnectionsReducer';

export default combineReducers({
newUser: postUser,
form: formReducer,
conexiones: ConnectionsReducer
});

我进行调用的组件如下所示:

import React, { Component } from 'react';
import { Grid, Container, Select, Button, withStyles, FormControl, InputLabel, MenuItem } from '@material-ui/core';
import {connect} from 'react-redux';
import {reduxForm, Field} from 'redux-form';


import {deleteConnection, getAllConnections} from '../actions';

const styles = theme => ({
root: {
display: 'flex',
flexWrap: 'wrap',
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
});

class BorrarConexion extends Component {

componentDidMount() {
this.props.getAllConnections();
}

handleSubmit = ({conexionId}) => {
this.props.deleteConnection(conexionId);
}

renderConexiones = () => {
return this.props.conexiones.map(conexion =>{
return (<MenuItem key={conexion.id} value={conexion.id}>{conexion.connectionUrl}</MenuItem>);
});
}

renderSelectField = ({input,label,meta: { touched, error },children,...custom}) =>{
return (
<FormControl>
<InputLabel>Seleccione la URL que desea eliminar</InputLabel>
<Select {...input} {...custom}>
{this.renderConexiones()}
</Select>
</FormControl>
)
}

render() {
return (
<Container>
<Grid container direction="column">
<Field name="conexionId" component={this.renderSelectField} label="Favorite Color"/>
<Button onClick={this.props.handleSubmit(this.handleSubmit)}>Eliminar</Button>
</Grid>
</Container>
);
}
}

const mapStateToProps = (state) => {
return {conexiones: state.conexiones}
}

const BorraConexionEstilizado = withStyles(styles)(BorrarConexion);
const formWrapped = reduxForm({form: 'delete_connection'})(BorraConexionEstilizado);

export default connect(mapStateToProps, {getAllConnections, deleteConnection})(formWrapped);

当我使用一个名为 getAllConnections 的单独 reducer 执行此操作并将 conexiones: ConnectionsReducers 替换为 conexiones: getAllConnections 时,它起作用了。 getAllConnections reducer 看起来像这样:

export default (state = [], { type, payload }) => {
switch (type) {

case 'GET_ALL_CONNECTIONS':
return payload

default:
return state
}
}

我想知道如何使用一个 reducer 接收我的所有操作而不是每个操作使用一个单独的 reducer 来完成这项工作。

最佳答案

这个问题与您可能从 reducer 返回不同的结构有关。看起来 reducer 旨在将对象作为状态处理,但对于这种情况,您返回一个数组。对象没有 map 功能。您需要确定此 reducer 的状态结构并坚持使用它,您不能从数组更改为对象然后再返回,这是 redux 不适合的不确定行为。

我不知道你们 API 的实现细节,但这是需要更新的主要领域

  const initialState = []

export default (state = initialState, { type, payload }) => {
switch (type) {

case GET_ALL_CONNECTIONS:
return payload //hoping that your api gave an array here

case POST_CONNECTION:
//return {...state, ...payload} //this is clearly returning an object
return [...state, payload] //now it returns an array with a new item

case DELETE_CONNECTION:
//return {...state, ...payload} //this is clearly returning an object
return state.filter(item => item.id !== payload.id) //now it returns a filtered array

default:
return state
}
}

以下代码应以数组形式接收状态并以数组形式返回更新后的状态。

关于javascript - 如何在 Redux 中使用 reducer 进行多个操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56842478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com