[英]How to bind to textfields without state in react/redux
I am a bit new to react/redux我对 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据我所知,状态在 redux 中是不可变的,但是在搜索组件绑定示例时,我一直看到诸如
<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.在回调中,值正在更改和更新,但是 UI 没有观察这些变量。
I guess this question is just a sanity check.我想这个问题只是一个健全的检查。 Is this acceptable in redux?这在 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:您可以使用中间件将Immutability Checkcheck添加到您的代码中:
In your configureStore.js:在您的 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())
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.