0
我在react/redux中,我想在后端数据库(即Mongo)中创建一条新记录,然后获取新创建的唯一标识创建记录后使用记录。我可以创建记录就好了,我想在调用create record动作的同一个函数中使用唯一的id。我无法弄清楚如何用平台的异步特性来做到这一点。React/Redux:在数据库中创建记录并访问新创建的记录
该记录是一个人(在一个名为People的集合中)。下面我包括我的代码:
- 与调用createPerson行动
- 调用节点API来创建记录
- 减速机代码的动作代码的功能组件。请注意,当节点API响应,它与新创建的记录响应,所以它增加了新创建的记录 商店的新状态
这里是调用操作的部件:
import React from 'react';
import { connect } from "react-redux"
import { createPerson } from '../../actions/peopleActions';
@connect(
(store) => {
return {
people: store.people.people,
};
},
(dispatch) => {
return {
createPerson:() => {
dispatch(createPerson());
}
}
}
)
export default class PeopleSearch extends React.Component {
createPerson =() => {
this.props.createPerson();
/*****************
This is where I want to be able to execute only once the new person
is created and get the ID of the newly created record. But currently,
this next line outputs the people array as it exists before the new
record is created.
*****************/
console.log("After createPerson, with: ", this.props.people);
};
render =() => {
return (
<div>
<button onClick={this.createPerson}>
Create Person
</button>
</div>);
}
}
这里是动作:
import axios from "axios";
import cookie from "react-cookie";
import config from "../config.js";
export function createPerson(fName, mName, lName, sexAtBirth, notes) {
const body = {
object: {
fName,
mName,
lName,
sexAtBirth,
notes
}
};
return (dispatch) => {
dispatch({type: "CREATE_PERSON"});
axios.post(config.api_url + "/api/v2/person/create", body, axiosConfig)
.then((response) => {
dispatch({type: "CREATE_PERSON_FULFILLED", payload: response.data})
})
.catch((err) => {
dispatch({type: "CREATE_PERSON_REJECTED", payload: err})
})
}
}
这里是我的减速器:
export default function reducer(
state={
people: [],
fetching: false,
error: null,
},
action = ""
) {
case "CREATE_PERSON": {
return {
...state,
fetching: true
};
}
case "CREATE_PERSON_FULFILLED": {
return {
...state,
fetching: false,
people: [
...state.people,
action.payload
]
};
}
case "CREATE_PERSON_REJECTED": {
return {
...state,
fetching: false,
error: action.payload
};
}
}
如果您需要更多的信息来帮助我,请告诉我。谢谢。