Answer the question
In order to leave comments, you need to log in
How to store data passed from bean method using mapDispatchToProps?
Good afternoon! There is an add() function (method) in the main SmallApp component. This function is called in another component - AddComponent.
If you use the store's dispatch function directly through the component's properties, then the code works fine and the data is stored in state through the reducer - this.props.store.dispatch(increase_number(this.props.current_number + value))
However, I want to use only the action creator in the code - increase_number without calling the dispatch function through storage properties - increase_number(this.props.current_number + value). How to do it? When using the mapDispatchToProps function in connect, the component is not rendered...
SmallApp.js
// import...
class SmallApp extends React.Component {
constructor(props){
super(props)
this.add = this.add.bind(this)
}
add(value){
this.props.store.dispatch(increase_number(this.props.current_number + value))
}
render(){
const {add} = this
return (
<div>
<AddComponent add = {add} />
</div>
)
}
}
const mapStateToProps = (state) => {
return {
current_number: state.current_number
}
}
const mapDispatchToProps = dispatch => {
return {
increase_number: (value) => dispatch(increase_number(value))
}
}
export default connect(mapStateToProps,mapDispatchToProps)(SmallApp)
// import...
const AddComponent = ({add}) => {
return (
<div>
<a onClick={() => add(10)}>Кликнуть!</a>
</div>
)
}
export default connect()(AddComponent)
Answer the question
In order to leave comments, you need to log in
// actions.js
export const increaseNumber = value => ({ type: 'INCREASE_NUMBER', value })
//reducer.js
...
case 'INCREASE_NUMBER':
return {...state, value: state.value + action.value}
...
// SmallApp.js
import { increaseNumber } from '..путь до/actions'
...
render(){
return (
<div>
<AddComponent add = {this.props.increaseNumber} />
</div>
)
}
...
export default connect(mapStateToProps, { increaseNumber })(SmallApp)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question