【发布时间】:2018-03-13 00:35:17
【问题描述】:
我的 thunk 动作似乎没有贯穿其核心逻辑。我从componentDidMount 提高了thunk 动作,但它不会反过来导致它运行:const response = await findOne(id)。
另外,我认为如果使用 redux-thunk,我不需要明确地将调度作为道具传递给 mapDispatchToProps,我认为我设置 thunk 的方式是调度已经可用于 thunk?而且我用过类似的其他动作,效果很好,为什么不是这个?
重击动作
export function fetchCompany(id) {
return async (dispatch) => {
try {
const response = await findOne(id)
if(response && response.body) {
const company = response.body
dispatch(companyReceived(company))
}
} catch(err) {
console.log("failed request in authenticate thunk action")
console.log(`error details: ${err.status} /n ${err}`)
}
}
}
容器 ......
import { fetchCompany } from '../../client/actions/company/CompanyAsyncActions'
class InterviewContainer extends Component {
async componentDidMount() {
await fetchCompany(this.props.params.companyId)
}
render(){
return (this.props.company && <Interview className='ft-interview' company={this.props.company} />)
}
}
const mapStateToProps = state => ({
company: state.company.company
})
const mapDispatchToProps = {
fetchCompany: fetchCompany
}
export default connect(mapStateToProps, mapDispatchToProps)(InterviewContainer)
过去,我没有将 (dispatch) 作为道具传递给 mapDispatchToProps,它运行良好。但我看到其他人都在这样做。如果我不这样做,我的代码过去是如何工作的?为什么这一次在上面的示例中不起作用?
看看另一个异步操作 thunk 容器和调用示例,它工作得很好,我在另一个容器中以同样的方式调用它
容器
class HomePageContainer extends Component {
constructor(){
super()
}
async componentDidMount() {
await this.props.fetchFeaturedCompanies()
await this.props.fetchCompanies()
await this.props.fetchCountries()
}
render(){
return (<HomePage className='ft-homepage'
featuredCompanies={this.props.featuredCompanies}
countries={this.props.countries}
companies={this.props.companies}
/>)
}
}
const mapStateToProps = state => ({
countries: state.country.countries,
companies: state.company.companies,
featuredCompanies: state.company.featuredCompanies
})
const mapDispatchToProps = {
fetchCountries: fetchCountries,
fetchCompanies: fetchCompanies,
fetchFeaturedCompanies: fetchFeaturedCompanies
}
export default connect(mapStateToProps, mapDispatchToProps)(HomePageContainer)
thunk 动作
export function fetchCompanies() {
return async (dispatch, getState) => {
const response = await find()
if(response && response.body) {
const companies = response.body
dispatch(companiesReceived(companies))
}
}
}
【问题讨论】:
-
如果您将函数对象作为
connect的mapDispatchToProps参数传递,则每个函数都包含在dispatch中,因此您的mapDispatchToProps不是问题。请参阅docs on connect 了解更多信息。
标签: javascript reactjs react-redux redux-thunk