V
V
venanen2019-07-29 17:37:29
React
venanen, 2019-07-29 17:37:29

Why doesn't the state come to connect()()?

I have a store, with a reducer, in which, by clicking on a button, I will dispatch the corresponding action. Everything works here.
Then I sign the other component like this:

const matchStateToProps = (state)=>{
  return {
    title: state.title,
    text: state.text
  }
}
export default connect(matchStateToProps)(Notes)

This code fails with an error
TypeError: Cannot read property 'title' of undefined
, the error is in
return {
    title: state.title,
    text: state.text
  }

Of course, I can check for state:
const matchStateToProps = (state)=>{
        if(!state) return {}
  return {
    title: state.title,
    text: state.text
  }
}
export default connect(matchStateToProps)(Notes)

And it does work, but it shouldn't.
store code:
import {createStore} from 'redux'
const notesReducer = (state = {text: "", title: ""}, action)=>{
  console.log(state)
  switch(action.type){
    case "ADD_NOTES":
      return {...state, "text" :action.text, "title":action.title}
    break;
    case 'NOTE_DID_LOAD':
      return {state}
    break;
    default:
      console.log("Unreal dispatching ", action)
  }
}
export default createStore(notesReducer);

PS In the matchStateToProps function, I output the state variable to the console, there is empty space at the first moment of time, although it should not be, did I set the initial state?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-29
@venanen

default:
  return state;

By default, the reducer should return the unmodified state.
The first argument to connect is properly named mapStateToProps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question