[英]ReactJS - Proper way to fetch data from redux and load form
I have the reducer:我有减速机:
const INITIAL_STATE = {
campaign_dates: {
dt_start: '',
dt_end: '',
},
I am submiting my form and them send an action to save the data into redux:我正在提交我的表单,他们发送一个操作将数据保存到 redux:
function onSubmit(data) {
dispatch(addCampaignDatesAction(data))
}
So far so good, I'm able to save the data, but how can I load it in my form?到目前为止一切顺利,我能够保存数据,但如何将其加载到我的表单中?
In my component where my form is, I tried something like this:在我的表单所在的组件中,我尝试了这样的事情:
const getCampaignDatesFromState = useSelector(
state => state.createCampaign.campaign_dates,
)
const [startDate, setStartDate] = useState(getCampaignDatesFromState.dt_start !== '' ? new Date(getCampaignDatesFromState.dt_start) : '')
const [endDate, setEndDate] = useState(getCampaignDatesFromState !== '' ? new Date(getCampaignDatesFromState.dt_end) : '')
But I'm getting "Invalid time value at format" error (my start and end date inputs is from react-datepicker)但是我收到“格式时无效的时间值”错误(我的开始和结束日期输入来自 react-datepicker)
What is the proper way to load redux data into your form?将 redux 数据加载到表单中的正确方法是什么?
İf you want to call dispatch and update your store you sould add this lines on your form ;如果你想打电话给 dispatch 并更新你的商店,你应该在你的表格上添加这行;
Firstly added bindActionCreators and connect;首先添加bindActionCreators和connect;
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
and then use connect method for mapStateToProps, mapDispatchToProps;然后对mapStateToProps、mapDispatchToProps使用connect方法;
export default connect(
mapStateToProps,
mapDispatchToProps
)(YourComponent);
now you sould define mapStateToProps, mapDispatchToProps like this;现在你应该像这样定义 mapStateToProps、mapDispatchToProps;
const mapStateToProps = state => ({
getCmpDates: state.campaign_dates
});
const mapDispatchToProps = dispatch => ({
setCmpDates: bindActionCreators(campaign_dates, dispatch),
});
and now you can change your store with setCmpDates or you can read dates with getCmpDates.现在您可以使用 setCmpDates 更改您的商店,或者您可以使用 getCmpDates 读取日期。
You need to use the connect()
method from the react-redux
library.您需要使用
react-redux
库中的connect()
方法。 This does also contain some hooks, but you are better off avoiding them, as they can create some strange problems and you loose all the performance benefits of connect
.这也包含一些钩子,但最好避免它们,因为它们会产生一些奇怪的问题,并且会失去
connect
所有性能优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.