我是 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
})
})
}
}
这是我的 reducer
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
}
};
关于javascript - Reactjs-Redux : Clearing forms without redux-form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228587/