React Redux store state change is not working

2019-08-04 07:38发布

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;

2条回答
放我归山
2楼-- · 2019-08-04 07:45

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));
}
查看更多
叼着烟拽天下
3楼-- · 2019-08-04 07:54

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.

查看更多
登录 后发表回答