Hello guys i learning Redux, but an error occurred. I can call the function fetchUsers and it will run . Necessarily it is necessary to use a dispatch?
import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import User from '../components/User'
import Page from '../components/Page'
import * as pageActions from '../actions/PageActions'
import * as getUser from '../actions/UserActions'
class App extends Component {
componentDidMount() {
const { dispatch } = this.props
const { fetchUsers} = this.props.getUser
dispatch(fetchUsers()) //**dispatch is not a function **
}
render() {
console.log(this)
const { data, page } = this.props
const { fetchUsers } = this.props.getUser
console.log('PROPS',this.props)
console.log(this.props.fetchUsers)
return <div className='row'>
<User data={data.data} getUser={fetchUsers} />
<Page photos={page.photos} year={page.year} fetching={page.fetching}/>
</div>
}
}
function mapStateToProps(state) {
console.log('mapStateToProps',state)
return {
data: state.user,
page: state.page
}
}
function mapDispatchToProps(dispatch) {
return {
pageActions: bindActionCreators(pageActions, dispatch),
getUser: bindActionCreators(getUser, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
I am not sure but I think you don't need to use dispatch, since you have used bindActionCreators in your mapDispatchToProps . Indeed you don't need to wrap it with an another dispatch, bindActionCreators is a helper that enable action creators to directly dispatch actions. So I think you can just invoke your action creator and it should automatically dispatch the action.
Correct if I'm wrong, this is a problem probably more related with react-redux than redux itself, next time I suggest you to ask help on StackOverflow I am sure there are people that will be able to help you too.
Please check out connect() examples:
https://github.com/reactjs/react-redux/blob/master/docs/api.md#examples
I think you don't need to use dispatch, since you have used bindActionCreators in your mapDispatchToProps .
This is correct.
You can either use dispatch and _not_ pass mapDispatchToProps, or you can use the props injected by mapDispatchToProps, and not use dispatch. This is why mapDispatchToProps is called this way—it lets you define some other props based on dispatch so you don’t need to use it again.
I also faced this kind of problem.
I tried to fix that problem by installing redux, but it didn't work.
Most helpful comment
Please check out
connect()examples:https://github.com/reactjs/react-redux/blob/master/docs/api.md#examples
This is correct.
You can either use
dispatchand _not_ passmapDispatchToProps, or you can use the props injected bymapDispatchToProps, and not usedispatch. This is whymapDispatchToPropsis called this way—it lets you define some other props based ondispatchso you don’t need to use it again.