reactjs - 如何从状态中获取 reduxFrom 的初始值?
问题描述
我正在使用我的表单和 react redux。我有相同的表格来编辑和创建一个新表格。
我希望,在打开我的表单时,如果进行编辑,我会从我的 api 中输入表单的初始值。
我已经尝试过官方文档,但它不起作用。
这是我的表格:
class Form extends Component {
componentDidMount () {
const tripId = this.props.match.params.uid;
if(tripId){
this.fetchData(tripId);
}
}
fetchData = async (tripId) => {
axios.defaults.headers.common['Authorization'] = 'token';
axios.defaults.headers.common['Accept'] = 'application/vnd.trips.v1+json';
await axios.get(`myurl`)
.then(res => {
const trip = res.data;
this.setState({
trip: trip,
isLoading: false,
initialValues: trip
});
})
console.log('Terminou de carregar')
}
(....)
Form = reduxForm({ form: 'trip', enableReinitialize : true })(Form)
const mapStateToProps = state => {
const { intl, vehicleTypes, users, dialogs, trip } = state
return {
intl,
vehicleTypes,
users,
dialogs,
initialValues: trip
}
}
export default connect(
mapStateToProps, { setDialogIsOpen }
)(injectIntl(withRouter(withTheme()(Form))))
但是我的 initialValues 永远不会被填充,并且总是空白。我调试了代码,我看到我的 API 正在加载并设置我的 fetchData 方法的状态。那么,我在这里做错了什么?
解决方案
首先,您尝试initialValues
通过this.setState
哪个不起作用,reduxForm 期望initialValues
以props
.
application state
需要提一下, and之间有区别component local state
,第一个 -application state- 显然是由 redux 管理的,另一个 -local component state- 是由 react 管理的,你可以通过调用来修改它this.setState
所以要解决这个问题,当你从你的 api 接收数据时,你应该调度一个动作,并更新你的道具mapStateToProps
您的代码应如下所示:
class Form extends Component {
componentDidMount () {
const tripId = this.props.match.params.uid;
if(tripId){
this.fetchData(tripId);
}
}
fetchData = async (tripId) => {
await axios.get(`https://toptal-backend-fmaymone.c9users.io/trips/${tripId}`)
.then(res => {
const trip = res.data;
this.props.fillTheForm(trip);
})
console.log('Terminou de carregar')
}
(....)
Form = reduxForm({ form: 'trip', enableReinitialize : true })(Form)
const mapStateToProps = state => {
const { intl, vehicleTypes, users, dialogs, trip } = state
return {
intl,
vehicleTypes,
users,
dialogs,
initialValues: trip
}
}
const fillTheForm = (dispatch) => (trip) => {
// here you dispatch the action and update your application state
// in your reducer when this action is dispatched,
// then mapStateToProps should be called and the data you just
// passed in your reducer should be in (state)
dispatch()
}
export default connect(
mapStateToProps, { setDialogIsOpen, fillTheForm }
)(injectIntl(withRouter(withTheme()(Form))))
推荐阅读
- c++ - 使用文件流时如何使程序工作而不管用户的密码?
- javascript - 教程 Luiztools | 错误 404:使用 MongoDB 的 Node.js 中的 CRUD
- node.js - npm 命令行错误:非法指令
- apache-spark - 如何在 RDD Pyspark 中转换数据类型?
- r - 嵌套 if 语句和逻辑与 R 中 csv 文件中的字符串
- json - JQ 将特定键的 JSON 转换为 CSV
- algorithm - MATLAB中遗传算法的即时收敛
- swift - 缩小文本的字体大小以使其长度适合 SwiftUI 中的另一个文本
- ruby-on-rails - 在 Ruby on rails 中使用 FCM 为 Web 应用程序推送通知
- c++ - 将 .cpp 和 .lib 编译成 WINDOWS 中的共享 .so 库