Answer the question
In order to leave comments, you need to log in
Losing this in mapDispatchToProps. Why doesn't dispatch have it?
Recently started digging into React/Redux and ran into a problem. I did connect everything as in the documentation, but I lose this in the dispatch method. At the same time, mapStateToProps works correctly.
Here is the code
import React from "react"
import { connect } from "react-redux"
class Interface extends React.Component{
constructor(props){
debugger
super(props)
this.props=props;
console.log(props);
this.elements=null;
}
render(){
if(this.props.todo.length>0){
this.elements=this.props.todo.map((value)=>{
return <li key={value}>{value}</li>
})
}
debugger
return(
<div>
<div><p>add</p><input type="text"
ref={this.props.add}></input>
<button onClick={this.props.foo}>add</button></div>
<div><p>remove</p><input type="text" ref={this.props.remove}></input></div>
<h1>Todo list</h1>
<ul>{this.elements}</ul>
</div>
)
}
}
function mapStateToProps(state) {
return{
add:React.createRef(),
remove:React.createRef(),
todo:state.todo,
}
}
function mapDispatchToProps(dispatch) {
return{
foo:()=>{
dispatch({type:"ADD",data:"data"})
}
}
}
let Cover = connect(mapStateToProps,mapDispatchToProps)(Interface)
export default Cover
dispatch(action){
switch (action.type) {
case ADD:{
debugger
this.state.todo=todoreducer(this.state.todo,action.data)
this.rerender()
break;
}
case REMOVE:{
this.state.done.push(action.data)
this.state.todo=donereducer(this.state.todo,action.data)
this.rerender()
break;
}
default:
break;
}
}
Answer the question
In order to leave comments, you need to log in
Damn, I don't even know what to say... Let's go in order
1) What materials do you teach? Are they really outdated? Your constructor really confuses me, because props are automatically written to this.props anyway. It turns out that instead of the whole method, you can simply write
class Interface extends React.Component{
elements = null;
...
}
dispatch(action){
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question