Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.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 redux成功提交表单后如何重定向_Javascript_Reactjs_Redux_React Redux_Redux Thunk - Fatal编程技术网

Javascript 使用react redux成功提交表单后如何重定向

Javascript 使用react redux成功提交表单后如何重定向,javascript,reactjs,redux,react-redux,redux-thunk,Javascript,Reactjs,Redux,React Redux,Redux Thunk,action.js import axios from 'axios'; import { EVENT_ADD_FAIL, EVENT_ADD_REQUEST, EVENT_ADD_SUCCESS } from '../constraints/eventConstraint'; const addEvent = (event) => async (dispatch) => { dispatch({ type: EVENT_ADD_REQUEST, payload: event }

action.js

import axios from 'axios';
import { EVENT_ADD_FAIL, EVENT_ADD_REQUEST, EVENT_ADD_SUCCESS } from '../constraints/eventConstraint';

const addEvent = (event) => async (dispatch) => {
 dispatch({ type: EVENT_ADD_REQUEST, payload: event });
 try {
    const { data } = await axios.post(`http://localhost:4000/event`, event);
    dispatch({ type: EVENT_ADD_SUCCESS, payload:data });
 }
 catch (error) {
    dispatch({ type: EVENT_ADD_FAIL, payload:error.message });
 };
};


export { addEvent };
constraint.js

export const EVENT_ADD_REQUEST = 'EVENT_ADD_REQUEST';
export const EVENT_ADD_SUCCESS = 'EVENT_ADD_SUCCESS';
export const EVENT_ADD_FAIL = 'EVENT_ADD_FAIL';
reducer.js

import {EVENT_ADD_FAIL, EVENT_ADD_REQUEST, EVENT_ADD_SUCCESS } from "../constraints/eventConstraint";

function eventAddReducer(state = {}, action) {
 switch(action.type) {
    case EVENT_ADD_REQUEST:
        return { loading: true };
    case EVENT_ADD_SUCCESS:
        return { loading: false, event: action.payload, success:true };
    case EVENT_ADD_FAIL:
        return { loading: false, error: action.payload, success:false };
    default:
        return state
 };
};

export { eventAddReducer }
store.js

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

const initialState = {};
const reducer = combineReducers({
  addEvent: eventAddReducer
});

const store = createStore(reducer, initialState, compose(applyMiddleware(thunk)));
export default store
event.js

import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useHistory } from 'react-router-dom';
import { addEvent } from '../actions/eventAction';

const AddEvent = () => {
 const history = useHistory();
 const [event, setEvent] = useState();
 const addNewEvent = useSelector(state => state.addEvent);
 console.log(addNewEvent)
 const dispatch = useDispatch();

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

 const submitHandler = async (e) => {
    e.preventDefault();
    await dispatch(addEvent(event));
 };

// if(addNewEvent.success === true) {   
//     history.push('/')
// };   ===========>>>>>>>>>>> It works at first but after submission first time next time it automatically redirects to '/' because react-redux holds state

return (
    <>
        <form onSubmit = { submitHandler } >
            <div className="form-group">
                <label htmlFor="name">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="price">Price:</label>
                <input type="text" className="form-control" id="price" name="price" onChange={e => handleChange(e)} />
            </div>
            <Link to='/'> <button type="button" className="btn btn-success"> Back </button> </Link>
            <button type="submit" className="btn btn-success float-right"> Add Event </button>
        </form>
    </>
 )
};

export default AddEvent
import React,{useState}来自“React”;
从'react redux'导入{useDispatch,useSelector};
从“react router dom”导入{Link,useHistory};
从“../actions/eventAction”导入{addEvent};
常量AddEvent=()=>{
const history=useHistory();
const[event,setEvent]=useState();
const addNewEvent=useSelector(state=>state.addEvent);
console.log(addNewEvent)
const dispatch=usedpatch();
常量handleChange=e=>{
setEvent({…事件,[e.target.name]:e.target.value})
};
const submitHandler=async(e)=>{
e、 预防默认值();
等待调度(附加事件(事件));
};
//如果(addNewEvent.success==true){
//history.push(“/”)
//};==========>>>>>>>>它开始工作,但在下次第一次提交后,它会自动重定向到“/”,因为react-redux保持状态
返回(
姓名:
handleChange(e)}/>
说明:
handleChange(e)}/>
价格:
handleChange(e)}/>
返回
添加事件
)
};
导出默认AddEvent

一切正常,但我想在成功提交表单后,它需要重定向到某个页面。它很简单,没有react-redux,我们可以在提交表单后简单地重定向,但我正在尝试学习redux,对redux知之甚少。我尝试在reducer中使用success=true,它在第一次工作时起作用,但由于redux保持状态,当我尝试打开链接时,它会自动重定向到主页,因为react redux保持success=true。任何帮助都将不胜感激。

首先:请确保每次操作重置
成功

function eventAddReducer(state = {}, action) {
  switch(action.type) {
     case EVENT_ADD_REQUEST:
         return { 
           loading: true,
           success: null // <-- Look at this
          };
    /** ... */
  };
};
使用挂钩

const AddEvent = ({ success }) => {
  useEffect(() => {
    if (success) {
      /** Redirect here */
    }
  }, [success]); // <-- This will make sure that the effect only runs when success variable has changed
};

const mapStateToProps = ({ addEvent: { success } }) => ({
  success
});

export default connect(mapStateToProps)(AddEvent);
constaddevent=({success})=>{
useffect(()=>{
如果(成功){
/**重定向到这里*/
}
},[成功];//({
成功
});
导出默认连接(MapStateTops)(AddEvent);

首先:确保每次操作重置
成功

function eventAddReducer(state = {}, action) {
  switch(action.type) {
     case EVENT_ADD_REQUEST:
         return { 
           loading: true,
           success: null // <-- Look at this
          };
    /** ... */
  };
};
使用挂钩

const AddEvent = ({ success }) => {
  useEffect(() => {
    if (success) {
      /** Redirect here */
    }
  }, [success]); // <-- This will make sure that the effect only runs when success variable has changed
};

const mapStateToProps = ({ addEvent: { success } }) => ({
  success
});

export default connect(mapStateToProps)(AddEvent);
constaddevent=({success})=>{
useffect(()=>{
如果(成功){
/**重定向到这里*/
}
},[成功];//({
成功
});
导出默认连接(MapStateTops)(AddEvent);

我知道这不是最理想的解决方案,但是创建一个可以重置成功并将其发送到useEffect中的操作如何

大概是这样的:

减速器

从“./constraints/eventConstraint”导入{事件添加失败、事件添加请求、事件添加成功};
函数eventAddReducer(状态={},操作){
开关(动作类型){
案例事件添加请求:
返回{loading:true};
案例事件添加成功:
返回{loading:false,event:action.payload,success:true};
案例事件添加失败:
返回{loading:false,error:action.payload,success:false};
案例重置:
返回{
……国家,
加载:false,
成功:错
}//这将重置一切,包括成功
违约:
返回状态
};
};
导出{eventAddReducer}
并在event.js文件中调用一个将分派重置的操作。确保将其放入useeffect中


从“React”导入React,{useState};
从'react redux'导入{useDispatch,useSelector};
从“react router dom”导入{Link,useHistory};
从“../actions/eventAction”导入{addEvent};
常量AddEvent=()=>{
const history=useHistory();
const[event,setEvent]=useState();
const addNewEvent=useSelector(state=>state.addEvent);
console.log(addNewEvent)
const dispatch=usedpatch();
React.useffect(()=>{
myResetAction()
}, [])
常量handleChange=e=>{
setEvent({…事件,[e.target.name]:e.target.value})
};
const submitHandler=async(e)=>{
e、 预防默认值();
等待调度(附加事件(事件));
};
//如果(addNewEvent.success==true){
//history.push(“/”)
//};==========>>>>>>>>它开始工作,但在下次第一次提交后,它会自动重定向到“/”,因为react-redux保持状态
返回(
姓名:
handleChange(e)}/>
说明:
handleChange(e)}/>
价格:
handleChange(e)}/>
返回
添加事件
)
)}

这样做会有帮助。

我知道这不是最理想的解决方案,但是创建一个可以重置成功并将其发送到useEffect中的操作如何

大概是这样的:

减速器

从“./constraints/eventConstraint”导入{事件添加失败、事件添加请求、事件添加成功};
函数eventAddReducer(状态={},操作){
开关(动作类型){
案例事件添加请求:
返回{loading:true};
案例事件添加成功:
返回{loading:false,event:action.payload,success:true};
案例事件添加失败:
返回{loading:false,error:action.payload,success:false};
案例重置:
返回{
……国家,
加载:false,
成功:错
}//这将重置一切,包括成功
违约:
返回状态
};
};
导出{eventAddReducer}
在event.js文件中调用一个操作,该操作将分派RESET。请确保将其放入useeffect中


从“React”导入React,{useState};
从'react redux'导入{useDispatch,useSelector};
从“react router dom”导入{Link,useHistory};
从“../actions/eventAction”导入{addEvent};
常量AddEvent=()=>{
常数历史