如何使用react hooks调用reducer中的重置类型

事件.js


import React, { useEffect, useState } from 'react';

import { useDispatch, useSelector } from 'react-redux';

import { Link, useHistory } from 'react-router-dom';

import { addEvent } from '../actions/event';


const AddEvent = () => {

let history = useHistory();

const [event, setEvent] = useState();

const createEvent = useSelector(state => {

    console.log(state)

    return (

        state.addEvent

    )

});

const { loading, newEvent, success, error } = createEvent;

const handleChange = e => {

    setEvent({ ...event, [e.target.name]: e.target.value });

};

const dispatch = useDispatch();

useEffect(() => {

    if(success) {

        history.push('/')  =========>>>>>>>> It work once fine but again when I tries to open add Event it automatically redirects to '/' as it is not getting reset after redirecting

    };

},[success]);

const submitHandler = (e) => {

    e.preventDefault();

    dispatch(addEvent(event));

};


return (

    <div>

        { loading ? (

            <div> Loading... </div>

        ) : error ? (

            <div> {error} </div>

        ) : (

                    <form onSubmit={e => submitHandler(e)}>

                        <div className="form-group">

                            <label htmlFor="name" className='mt-2'>Name</label>

                            <input type="text" className="form-control" id="name" name="name" onChange={e => handleChange(e)} />

                        </div>

                        <div className="form-group">

                            <label htmlFor="description">Description</label>


我正在学习如何使用 React Redux,所以我尝试 CRUD 工作流程工作正常,但在成功添加事件后,我希望它重定向到主页,它工作正常,但由于 React-Redux 保持其状态,因此它再次成功重定向到主页设置为 true 所以我创建了另一个重置类型以将 success 设置为 false 但不知道如何在成功添加数据后每次调用


慕姐4208626
浏览 86回答 1
1回答

拉丁的传说

动作.jsconst addEvent = (newEvent) => async (dispatch) => {dispatch({ type: EVENT_ADD_REQUEST, payload:newEvent });&nbsp;try {&nbsp; &nbsp; const { data } = await axios.post(`http://localhost:3002/event`, newEvent);&nbsp; &nbsp; dispatch({ type: EVENT_ADD_SUCCESS, payload: data });&nbsp; &nbsp; dispatch({ type: EVENT_RESET });&nbsp; ===>>> adding here it works&nbsp;}&nbsp;catch (error) {&nbsp; &nbsp; dispatch({ type: EVENT_ADD_FAIL, payload:error.message });&nbsp;}};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript