简体   繁体   中英

React-redux dispatch function with parameters from child component is undefined

I have an action

export const saveNewTask = (taskName, taskDescription) => async dispatch => {
  console.log(taskName, taskDescription);
  const res = await axios.post('/api/add-new-task', {
    taskName,
    taskDescription
  });
  console.log(res);
  dispatch({ type: SAVE_TASK, payload: res.data });
};

a parent container that contains a child container which is a Formik form and should allow the child component to save the Formik form contents to the db via the above mentioned action.

import { saveNewTask } from '../actions/index';

class ClientDashboard extends React.Component {
  render() {
    return <NewTask saveNewTask={saveNewTask()} />;
  }
}

export default connect(null, { saveNewTask })(Container);

NewTask.js child component that does not know anything about Redux:

function NewTask(props) {
  const formik = useFormik({
    initialValues: {
      taskName: '',
      taskDescription: ''
    },
    onSubmit: values => {
      // alert(JSON.stringify(values, null, 2));
      props.saveNewTask(values.taskName, values.taskDescription);
    }
  });
...
}

but the action never gets the parameters that I am trying to pass through the Formik component (the commented alert line displays both values perfectly) and says both taskName and taskDescription are undefined. Also the dispatch in the last line of the action says

Uncaught (in promise) TypeError: dispatch is not a function at Object.saveNewTask

I think this is more of a syntax error than anything else but any help would be greatly appreciated.

The problem is in this line:

return <NewTask saveNewTask={saveNewTask()} />;
  1. You need to pass a prop for calling the action , not the result of the function call.
  2. You need to call your prop, not your action creator method.

So, change that line to:

return <NewTask saveNewTask={this.props.saveNewTask} />;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM