[英]Reactjs - Redux: Clearing forms without redux-form
我是redux的新手,我在不使用redux-form的情况下制作组件。 有没有一种方法可以不使用redux-form来清除任何表单? 例如,我输入了abcd
并单击了提交按钮,如果提交成功,则应清除/清除输入字段。
这是我的组成部分
import React, { Component } from 'react' import { connect } from 'react-redux' import { saveSomething } from '../../actions' class InputSomething extends Component { state={ inputValue: "" } handleInput = (key, e) => { this.setState({[key]: e.target.value}) } save(){ this.props.saveSomething() } render(){ return( <input type="text" value={this.state.inputValue} onChange={this.handleInput.bind(this, 'inputValue')}/> <input type="submit" onClick={this.save}/> )} } const mapStateToProps = state => { return { saveRetun: state.saveReturn } } export default connect(mapStateToProps, { saveSomething })(InputSomething)
这是我的行动
import axios from 'axios' import { SAVE_SOMETHING, SAVE_SOMETHING_SUCCESS, SAVE_SOMETHING_FAILED } from './types' export const saveSomething = () =>{ var url = '/someurlhere' return(dispatch)=>{ dispatch({type:SAVE_SOMETHING}) axios.post(url) .then((res)=>{ dispatch({ type:SAVE_SOMETHING_SUCCESS, payload:res.data }) }) .catch((error)=>{ dispatch({ type:SAVE_SOMETHING_FAILED, payload:error }) }) } }
这是我的减速器
import { SAVE_SOMETHING, SAVE_SOMETHING_SUCCESS, SAVE_SOMETHING_FAILED } from '../actions/types' const INITIAL_STATE = { loading: true, data : [], error: '' , success: false }; export default (state = INITIAL_STATE, action) => { switch (action.type){ case SAVE_SOMETHING: return {...state, loading: true} case SAVE_SOMETHING_SUCCESS: return {...state, loading: false, data: action.payload, success: true} case SAVE_SOMETHING_FAILED: return {...state, loading: false, error: action.payload, success: false} default: return state } };
提前致谢 :)
您只需要使用成功的初始数据来重新初始化组件。
export default (state = INITIAL_STATE, action) => {
switch (action.type){
case SAVE_SOMETHING:
return {...state, loading: true}
case SAVE_SOMETHING_SUCCESS:
// reset to initial data
return {data: [], loading: false, success: true}
case SAVE_SOMETHING_FAILED:
return {...state, loading: false, error: action.payload, success: false}
default:
return state
}
};
save(){
this.props.saveSomething().then(this.setState({inputValue:''}))
}
上面的代码会将状态设置为空白。
save(){
this.props.saveSomething()
.then(this.setState({inputValue:''}), this.forceUpdate())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.