在redux中拦截异步操作
我正在使用react with redux构建一个简单的notes应用程序。我的创建笔记操作如下所示:在redux中拦截异步操作,redux,react-redux,Redux,React Redux,我正在使用react with redux构建一个简单的notes应用程序。我的创建笔记操作如下所示: import axios from "axios"; const URL = 'http://localhost:3002/api/'; export function createNote(data = {}) { return { type: 'CREATE_NOTE', payload: axios.post(URL + 'notes/', d
import axios from "axios";
const URL = 'http://localhost:3002/api/';
export function createNote(data = {}) {
return {
type: 'CREATE_NOTE',
payload: axios.post(URL + 'notes/', data),
};
}
我的减速器中有以下部件:
// Create
case 'CREATE_NOTE_PENDING':
{
return {
...state,
creating: true
};
}
case 'CREATE_NOTE_FULFILLED':
{
return {
...state,
creating: false,
notes: action.payload.data
};
}
case 'CREATE_NOTE_REJECTED': {
return {
...state,
creating: false,
error: action.payload
};
}
这是我的笔记课:
function mapStateToProps(store) {
return {
data: store.note.notes,
fetching: store.note.fetching,
creating: store.note.creating,
error: store.note.error,
};
}
class Notes extends Component {
componentWillMount() {
this.props.dispatch(fetchNotes());
}
create() {
this.props.dispatch(createNote({
title: this.refs.title.value,
content: this.refs.content.value,
}));
this.refs.title.value = '';
this.refs.content.value = '';
}
render() {
return (
<div className="App">
<h1 className="text-center">Notepad</h1>
<div className="row">
<div className="col-md-6 col-md-offset-3">
<div className="form-group">
<input ref="title" placeholder="Create a note" className="form-control" disabled={this.props.creating} />
</div>
<div className="form-group">
<textarea ref="content" className="form-control" disabled={this.props.creating} />
</div>
<button onClick={this.create.bind(this)}
type="submit"
className="btn btn-primary"
style={{float: 'right'}}
disabled={this.props.creating} >Save</button>
</div>
</div>
函数MapStateTops(存储){
返回{
数据:store.note.notes,
抓取:store.note.fetching,
创建:store.note.creating,
错误:store.note.error,
};
}
类注释扩展了组件{
组件willmount(){
this.props.dispatch(fetchNotes());
}
创建(){
this.props.dispatch(createNote({
标题:this.refs.title.value,
内容:this.refs.content.value,
}));
this.refs.title.value='';
this.refs.content.value='';
}
render(){
返回(
便条簿
拯救
不在创建时我将禁用表单,直到我从服务器获得答案并重置表单中的内容。我的问题是当我得到响应时,即表单启用时,如何重置表单的内容?如果要控制输入和文本区域的内容,应使用受控组件。That用于提供值属性,例如输入
<input value={this.state.title} placeholder="Create a note" className="form-control" disabled={this.props.creating} />
您可以对值使用内部状态或redux状态。然后您可以通过设置状态或redux操作来控制值。您的回答非常有用!谢谢!