我有这个代码,它为我的API返回一个thunk
import { SUBSCRIBE_REQUEST, SUBSCRIBE_SUCCESS, SUBSCRIBE_FAILURE } from '../../constants'
export function subscribeUser (data) {
return (dispatch, getState, { axios }) => {
dispatch({ type: SUBSCRIBE_REQUEST })
return axios.get(`some/api/call`, data)
.then(res => {
dispatch({
type: SUBSCRIBE_SUCCESS,
payload: res.data
})
})
.catch(error => {
dispatch({
type: SUBSCRIBE_FAILURE,
payload: error,
error: true
})
})
}
}我现在正在实现react-redux-form,不清楚如何将上面的内容与提交函数连接起来。从他们的文档中,它希望我在提交操作中传递一个承诺:
class myForm extends React.Component {
handleSubmit (data) {
const { dispatch } = this.props
dispatch(actions.submit('user', somePromise))
}基本上是这样的:
dispatch(actions.submit('user', subscribeUser))如何将我的thunked API代码与提交处理程序连接起来?我已经考虑过redux-promise作为一种可能性,尽管我不清楚它是否能解决我的问题,如果我能工作的话,我也想保留现有的thunk代码库。
发布于 2016-10-06 12:07:37
注意:该示例使用React-Native,但它作为React组件工作,因为reducers和actions是相同的。
使用react-redux,您可以使用connect将actions和reducers的props链接到您想要的class。使用redux,您可以将操作绑定到您的操作。看起来是这样的
import React, { Component, PropTypes } from 'react';
import { View } from 'react-native';
import { User, Button, Header } from '../components';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as app from '../../actions/appActions';
class Home extends Component {
componentWillMount() {
this.props.actions.load(); //This will call the actions load. this.props.action will contain subscribeUser if you declare in down mapDispatchToProps
} }
//Whatever the render
render() {
return (
<View />
);
}
}
//PROPS VALIDATION
Home.propTypes = {
users: PropTypes.object.isRequired,
actions: {
load: PropTypes.func.isRequired,
},
};
//LINK STATE FROM REDUCER TO THIS CLASS. NEED TO DO PROPS VALIDATION
function mapStateToProps(state) {
return {
users: state.app.users,
};
}
//LINK ACTIONS TO THE CLASS SO YOU CAN USE IT LIKE IF IT WAS A PROPS. NEED TO DO PROPS VALIDATION
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(app, dispatch),
};
}
//CONNECT PROPS AND ACTION TO COMPONENT AS PROPS
export default connect(mapStateToProps, mapDispatchToProps)(Home);基本上,这在组件周围放置了一个更高级别的组件
https://stackoverflow.com/questions/39885229
复制相似问题