React Redux store state change is not working

人走茶凉 提交于 2020-01-15 08:55:22

问题


The below super simple code is not working as expected.

I am using react and injecting/providing props via redux store. what my understanding is store inject props in the React component.

To make this component work why I need both line1 and line 2 ?

import React from 'react';
import './sytles.css';
import { fetchUsers } from "./actions/userAction"
import { connect } from "react-redux"

@connect((store) => {
    return {
        signup: store.users,
    };
  })
class Signup extends React.Component {

    handleClick(event) {
       this.setState({email: event.target.value}) //line 1
       this.props.signup.email = event.target.value; // line 2
    }
    render() {
        return (
                <input
                    type="text"
                    name="email"
                    value={this.props.signup.email}
                    onChange=
                    { (event) => this.handleClick(event) }/>
        );
    }

}
export default Signup;

回答1:


You can't reassign props -- it's read only even aside from Redux. But to change the Redux store, you dispatch an action. Per the Redux documentation of The Three Principles of Redux:

State is read-only

The only way to change the state is to emit an action, an object describing what happened.

This ensures that neither the views nor the network callbacks will ever write directly to the state. Instead, they express an intent to transform the state. Because all changes are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for. As actions are just plain objects, they can be logged, serialized, stored, and later replayed for debugging or testing purposes.




回答2:


You are doing it incorrectly, props must never be mutated directly, also you shouldn't keep a state that is directly derivable from props. Since your data signup is present in store, you need an action creator that updates this value in the store

const handleSignup = (email) => {
   return {
       type: "SIGNUP_EMAIL",
       email
   }
}

and dispatch it like

handleClick(event) {
   dispatch(handleSignup(event.target.value));
}


来源:https://stackoverflow.com/questions/47970400/react-redux-store-state-change-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!