S
S
Sergey2020-11-12 22:15:42
React
Sergey, 2020-11-12 22:15:42

Why is the value in props after mapStateToProps undefined?

There is a Settings component

class Settings extends React.Component {
  
  constructor(props) {
    super(props);
  }

  handleClick() {
    this.props.changeTextAction();
  }

  render() {
    return (
      <div className="components-page">
        <Button color="primary" onClick={this.handleClick.bind(this)}>Кнопка</Button>
        <span>{this.props.someText}</span> 
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    someText: state.someText,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    changeTextAction: () => dispatch(changeText()),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Settings);


There is a reducer
const initialState = {
    isEmail: false,
    someText: 'Хороший текст'
}

export default function settingsReducer(state = initialState, action) {
    switch (action.type) {
        case 'changeText':
            return {
                ...state,
                someText: action.newText
            }

        default:
            return state
    }
}


and the action itself
export function changeText() {

    return {
        type: 'changeText',
        newText: 'Отличный текст'
    }
}


On click, someText changes according to devtools, but why can't I see it in {this.props.someText}? And why is the span initially empty too, instead of containing "Nice text"?
5fad8977dd757153517708.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twolegs, 2020-11-13
@DaveGarrow

Because someText is not at the root of the object. We need to get state.settingsReducer.someText

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question