I
I
Incold2020-02-14 23:55:25
React
Incold, 2020-02-14 23:55:25

Why doesn't the value in the child component change the first time?

Hello! I recently started learning React + Redux, and as it often happens, I ran into a problem.
I have a Redux store and an Auth parent component:

class Auth extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...}
    };
    this.formRef = React.createRef();
  }
  ...
  render() {
    return (
      <div>
        <form id="auth" ref={this.formRef}>
         <SignIn methods={this.state.methodsForReg} inputs={this.state.inputs}  logValue={this.props.logValues}/>
          {console.log(this.props.logValues)} // Здесь всё хорошо, т.е. при изменении состояния меняется значение свойства
        </form>
      </div>
    )
  }
}

export default connect(
  state => ({
    ...
    logValues: state.loginValue
  }),
  dispatch => ({...})
)(Auth);

There is also a child component SignIn:
class SignIn extends React.Component {
  render() {
    return(
      <div>
        ...
          <div className="col-6 text-right">
            <button className="btn btn-outline-success" onClick={(event)=>{
              this.props.methods.check(this.props.inputs, event);  //Этот метод меняет значение
              console.log(this.props.logValue); // Здесь, если первый раз нажать на кнопку, значение не поменяется, но со вторым нажатием всё норм
              this.props.loginUser(); // В этом action стоит console.log на нужное значение, и он работает нормально
            }}>Sign in</button>
          </div>
        </div>
      </div>
    )
  }
}

export default connect(
  state => ({}),
  dispatch => ({
    loginUser () {
      dispatch({type:'LOGIN'});
    }
  })
)(SignIn);

I also tried passing the logValue directly through the connect state in SignIn, but the result is the same.
Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Max, 2020-02-16
@Incold

When the onClick is triggered, the data in the editor changes through this.props.methods.check(), but since the props and state have not yet been updated, the component has not yet been redrawn. Because inside onClick console.log(this.props.logValue); output is not what you expect. And inside loginUser() you see the updated value, because you are probably pulling the getState() method in the action, which returns the current redax state.
That's actually all

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question