Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用react钩子调用reducer中的reset type_Javascript_Reactjs_Redux_React Redux - Fatal编程技术网

Javascript 如何使用react钩子调用reducer中的reset type

Javascript 如何使用react钩子调用reducer中的reset type,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,event.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 hi

event.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>
                            <input type="text" className="form-control" id="description" name="description" onChange={e => handleChange(e)} />
                        </div>
                        <div className="form-group">
                            <label htmlFor="userId">Assosicated User</label>
                            <input type="text" className="form-control" id="userId" name='userId' onChange={e => handleChange(e)} />
                        </div>
                        <Link to='/'> <button type="submit" className="btn btn-primary">Back</button> </Link>
                        <button type="submit" className="btn btn-primary float-right">Add Event</button>
                    </form>
                )}
    </div>
 )
};

export default AddEvent;
reducer.js

function addEventReducer(state = {}, action ) {
switch(action.type) {
    case EVENT_ADD_REQUEST:
        return { loading: true, success:false };
    case EVENT_ADD_SUCCESS:
        return { loading:false, newEvent: action.payload, success:true };
    case EVENT_ADD_FAIL:
        return { loading:false, error: action.payload, success: false };
    case EVENT_RESET:
        return { ...state, loading:false, success: false };  ===========>>>>>>>> I want to call this for reset success to false so that it does not redirect again
    default:
        return state;
 };
};
export {
 addEventReducer
};
store.js

import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { addEventReducer} from './reducers/event';

const reducer = combineReducers({
 addEvent: addEventReducer
});

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
 reducer,
 composeEnhancer(applyMiddleware(thunk))
);

export default store;
我正在学习使用react-redux,因此我尝试crud工作流工作正常,但在成功添加事件后,我希望它重定向到主页,它工作正常,但由于react-redux保持其状态,因此它将再次重定向到主页,因为成功设置为true,所以我创建了另一个重置类型,将成功设置为false,但未获得成功在成功添加数据后如何调用everytime

action.js

const addEvent = (newEvent) => async (dispatch) => {
 dispatch({ type: EVENT_ADD_REQUEST, payload:newEvent });
 try {
    const { data } = await axios.post(`http://localhost:3002/event`, newEvent);
    dispatch({ type: EVENT_ADD_SUCCESS, payload: data });
 }
 catch (error) {
    dispatch({ type: EVENT_ADD_FAIL, payload:error.message });
 }
};
export {
 addEvent
};
const addEvent = (newEvent) => async (dispatch) => {
dispatch({ type: EVENT_ADD_REQUEST, payload:newEvent });
 try {
    const { data } = await axios.post(`http://localhost:3002/event`, newEvent);
    dispatch({ type: EVENT_ADD_SUCCESS, payload: data });
    dispatch({ type: EVENT_RESET });  ===>>> adding here it works
 }
 catch (error) {
    dispatch({ type: EVENT_ADD_FAIL, payload:error.message });
 }
};