在这种情况下,您如何从减速器/动作正确调用函数?

凯西·考夫曼

我试图调用的动作/减速器不起作用。它似乎并没有真正按照我调用它的方式读取函数。问题出在 deleteWorkout 函数中。

我试过使用 mapDispatchToProps 并且我试过直接从动作中调用动作。src - index.js

import React from 'react';
import { createStore } from 'redux';
import allReducer from './reducers';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import throttle from 'lodash/throttle';
// import registerServiceWorker from './registerServiceWorker';
import App from './App';
import { loadState, saveState } from './localStorage';

const persistedState = loadState();

const store = createStore(
    allReducer,
    persistedState,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

store.subscribe(throttle(() => {
    saveState({
        workoutList: store.getState().workoutList
    });
}, 100));

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root')
);
// registerServiceWorker();

减速器 - index.js

import { combineReducers } from 'redux'
import switchLogin from './SwitchLogin'
import workoutList from './WorkoutList'
import { reducer as AddWorkout } from 'redux-form'

const allReducers = combineReducers({
    switchLogin,
    workoutList,
    form: AddWorkout,
})

export default allReducers;

锻炼项目类

import React, { Component } from "react";

import ExpansionPanel from "@material-ui/core/ExpansionPanel";
import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
import ExpansionPanelActions from "@material-ui/core/ExpansionPanelActions";

import TableHead from "@material-ui/core/TableHead";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import Table from "@material-ui/core/Table";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
// import { MuiThemeProvider } from "material-ui/styles";

import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
import ExerciseList from "./ExerciseList";

// import EditWorkoutItem from "./EditWorkoutItem";
import * as workoutActionCreators from '../../actions';
import { bindActionCreators } from 'redux';
import { connect } from "react-redux";

import moment from "moment";

export default class WorkoutItem extends Component {
  state = {
    open: false
  };

  handleSelectedPanel = () => {
    this.props.onSelectedPanel(this.props.workout.id);
  };

  // Opens the page
  handleClickOpen = () => {
    this.setState({ open: true });
  };

  // Cancels the changes and closes the page
  handleClose = () => {
    this.setState({ open: false });
  };

  deleteWorkout = id => {
    console.log(this);
    this.setState({ open: false });
    this.props.removeWorkout(id);
  };

  render() {
    const { workout } = this.props;
    const { id, name, duration, exerciselist } = workout;
    const date = moment(workout.date).format("L");

    return (
      <ExpansionPanel style={styles.panel} id={id} onChange={this.handleSelectedPanel}>
        <ExpansionPanelSummary>
          <Typography variant="button" style={styles.header}>
            {name}
          </Typography>
          <Typography variant="button" style={styles.header}>
            {date}
          </Typography>
          <Typography align="right" style={styles.header}>
            ~{duration} mins
          </Typography>
        </ExpansionPanelSummary>
        <ExpansionPanelDetails>
          <Table size="medium" style={styles.table}>
            <TableHead>
              <TableRow>
                <TableCell padding="none">Name</TableCell>
                <TableCell padding="none" align="right">
                  # of sets
                </TableCell>
                <TableCell padding="none" align="right">
                  average reps
                </TableCell>
                <TableCell padding="none" align="right">
                  weight
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {exerciselist.map(exercise => (
                <ExerciseList key={exercise.id} exercise={exercise} />
              ))}
            </TableBody>
          </Table>
          <ExpansionPanelActions disableSpacing style={styles.actionButton}>
            {/* <MuiThemeProvider>
              <EditWorkoutItem id={id} />
            </MuiThemeProvider> */}
            <>
              <Button size="small" disableRipple onClick={this.handleClickOpen}>
                Remove
              </Button>
              <Dialog
                open={this.state.open}
                onClose={this.handleClose}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
              >
                <DialogTitle id="alert-dialog-title">
                  {"Are you sure?"}
                </DialogTitle>
                <DialogContent>
                  <DialogContentText id="alert-dialog-description">
                    This will permanently remove the workout. This action cannot
                    be undone.
                  </DialogContentText>
                </DialogContent>
                <DialogActions>
                  <Button onClick={this.handleClose} color="primary">
                    Cancel
                  </Button>
                  <Button
                    onClick={() => this.deleteWorkout(id)}
                    color="primary"
                    autoFocus
                  >
                    Yes, Remove It
                  </Button>
                </DialogActions>
              </Dialog>
            </>
          </ExpansionPanelActions>
        </ExpansionPanelDetails>
      </ExpansionPanel>
    );
  }
}

const mapDispatchToProps = dispatch => {
  return { ...bindActionCreators(workoutActionCreators, dispatch) };
};

connect(
  null,
  mapDispatchToProps
)(WorkoutItem);

行动:

export const removeWorkout = id => ({ type: 'REMOVE_WORKOUT', id })

减速器:

        case 'REMOVE_WORKOUT':
            console.log(action.id)
            return state = {
                ...state,
                workoutlist: state.workoutlist.filter((workout) => workout.id !== action.id)
        }

没有错误信息。但是当我使用 console.log 时它返回正确的 id 并且它确实关闭了文本框。这就是我知道它在函数处停止的方式

香味

第一个主要问题是您调用的不是正确的“调度程序”函数,而是原始函数。

将您的 deleteWorkout 更改为:

deleteWorkout = id => {
    console.log(id);
    this.setState({ open: false });
    this.props.removeWorkout(id);
  };

第二个主要问题是您没有导出已连接的 Redux 容器,而是导出仍未连接到 Redux 的 React 组件。

从您的类声明中删除“导出默认值”:

class WorkoutItem extends Component {
// ...

并将其添加到 Redux 容器中:

export default connect(
    null,
    mapDispatchToProps
)(WorkoutItem);

编辑(这是实现 bindActorCreators 函数思想的可选更改。bindActorCreators 也可以将单个动作创建者作为第一个参数)。而且似乎您将单个动作创建者作为第一个参数传递给 redux 函数 bindActionCreators,但该函数取而代之的是动作创建者的映射。https://redux.js.org/api/bindactioncreators

您有两个选择如何修复它:

  1. 不要使用 bindActionCreators (如果你是 redux 初学者最好)
const mapDispatchToProps = dispatch => {
  return { removeWorkout: (id) => dispatch(removeWorkout(id)) };
};
  1. 正确使用 bindActionCreators
// you need to import your action crerators in single object
import * as workoutActionCreators from 'path_to_your_action_creators';

// ...

// bind all action creators with dispatch function and the bound action creators map to props
const mapDispatchToProps = dispatch => {
  return { ...bindActionCreators(workoutActionCreators, dispatch) };
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Bash-在这种情况下如何调用函数

我怎么能在这种情况下正确调用构造函数?

如何正确使用泛型在这种情况下?

在这种情况下如何正确显示

在这种情况下如何正确查询?

在这种情况下如何正确使用qmake?

在这种情况下如何正确使用自动版式?

如何在这种情况下正确使用Getter

在这种情况下,如何正确使用SQL COUNT()函数?

Django:在这种情况下如何使用聚合器

在这种情况下如何撰写

在这种情况下,为什么编译器会选择不正确的函数重载?

在这种情况下,AVG()函数的正确用法是什么?

如何在不使用路由的情况下从反应中访问特定的减速器变量作为道具

如何在不遍历状态的情况下访问减速器中的 redux 状态数组属性

如何在没有减速器的情况下从深度嵌套的子组件更新祖先状态

为什么在这种情况下未正确设置侦听器

为什么在这种情况下没有调用最合适的构造函数?

在这种情况下合并是否正确?

在这种情况下使用Redis池的正确方法

jQuery:在这种情况下,.on()的正确用法是什么?

在这种情况下正确使用移动语义?

在这种情况下,如何将div附加在正确的位置

在这种情况下,如何按类型正确进行模式匹配?

Java-在这种情况下如何正确规避非法访问异常

在这种情况下如何正确循环通过缓冲通道?

不知道在这种情况下如何正确使用Matrix4.LookAt

在这种情况下如何正确使用泛型和类型约束?

在这种情况下,如何使v-flex正确使用填充高度?