使组件可用的 thunk 操作的惯用方式?
Idiomatic way of making a thunk action available to components?
我编写了以下 thunk 动作创建器,用于向 api 发出请求。
如果我的理解是正确的,thunk action creator 将由中间件处理并可以访问 store dispatch 方法。
使这个 thunk 动作创建器可用于 React 组件的惯用方法是什么?
我能想到的最好的方法就是直接导入thunk action creator。
export function fetchMovie(title) {
return (dispatch) => {
dispatch(requestMovie(title));
const url = `http://www.omdbapi.com/?t=${title}&y=&plot=short&r=json`
return axios.get(url)
.then(response => {
dispatch(receiveMovie(title, response.data))
})
.catch(err => dispatch(requestMovieErr(title, err)))
}
}
是的,你的假设是正确的。最常见的方法是根据需要将单独的操作函数导入到您的组件中,例如:
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
// step 1: import action 'fetchMovie'
import { fetchMovie } from './actions/whateverYourFileIsCalled';
class SomeComponent extends Component {
render() {
return (
<div>
{/*
step 3: use the 'fetchMovie' action
that is now part of the component's props
wherever we'd like
*/}
<button onClick={this.props.fetchMovie.bind(null, 'Jurassic Park')}>
Click here for dinosaurs
</button>
</div>
);
}
}
SomeComponent.propTypes = {
fetchMovie: PropTypes.func.isRequired
};
export default connect(
{},
{
// step 2:
// connect the 'fetchMovie' action to this component's props using redux helper
fetchMovie
}
)(SomeComponent);
我编写了以下 thunk 动作创建器,用于向 api 发出请求。
如果我的理解是正确的,thunk action creator 将由中间件处理并可以访问 store dispatch 方法。
使这个 thunk 动作创建器可用于 React 组件的惯用方法是什么?
我能想到的最好的方法就是直接导入thunk action creator。
export function fetchMovie(title) {
return (dispatch) => {
dispatch(requestMovie(title));
const url = `http://www.omdbapi.com/?t=${title}&y=&plot=short&r=json`
return axios.get(url)
.then(response => {
dispatch(receiveMovie(title, response.data))
})
.catch(err => dispatch(requestMovieErr(title, err)))
}
}
是的,你的假设是正确的。最常见的方法是根据需要将单独的操作函数导入到您的组件中,例如:
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
// step 1: import action 'fetchMovie'
import { fetchMovie } from './actions/whateverYourFileIsCalled';
class SomeComponent extends Component {
render() {
return (
<div>
{/*
step 3: use the 'fetchMovie' action
that is now part of the component's props
wherever we'd like
*/}
<button onClick={this.props.fetchMovie.bind(null, 'Jurassic Park')}>
Click here for dinosaurs
</button>
</div>
);
}
}
SomeComponent.propTypes = {
fetchMovie: PropTypes.func.isRequired
};
export default connect(
{},
{
// step 2:
// connect the 'fetchMovie' action to this component's props using redux helper
fetchMovie
}
)(SomeComponent);