简体   繁体   中英

How to bind to textfields without state in react/redux

I am a bit new to react/redux

From what I understand state is to be immutable in redux, but when searching for component binding examples I keep seeing things such as

<TextField
  id="usernameId"
  value={this.state.username}    
  onChange={this.handleUsernameChange}
/>

public handleUsernameChange = (event: any) => {
        this.setState({
            username: event.target.value
        });
}

To my understanding this is mutating State. When I change the binding to use a global instead. In the callbacks the values are being changed and updated, however the UI is not observing these variables.

I guess this question is just a sanity check. Is this acceptable in redux?

Please note I am not using other libraries at the moment

Code I've tried without using state

   let loginInfomation: ILoginInformation = new LoginInformation;
...
   <TextField
      id="usernameId"
      value={this.loginInformation.username}    
      onChange={this.handleUsernameChange}
    />

    public handleUsernameChange = (event: any) => {
          this.loginInfomation.username = event.target.value
       });
    }

Strings are primitive types, and they are immutable by default.
You want to look out from mutating Objects and Arrays which are reference type.

This is OK:

let x = 8;
x = 5; // no mutation here

This is considered mutation:

let arr = [1,2,3];
arr.push(4); // this is mutating the existing array

So with reference types you can create new Objects or arrays:

let arr = [1,2,3];
let arr2 = [...arr, 4]; // creating new array;

You can use a Middleware to add Immutability Checkcheck to your code:

In your configureStore.js:

import { createStore, applyMiddleware } from 'redux';
import reducers from '../reducers';
import immutableCheckMiddleWare from 'redux-immutable-state-invariant';

export function configureStore(initialState) { 
     return createStore(
       rootReducer,
       initialState,
       applyMiddleware(immutableCheckMiddleWare())
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM