[英]How to bind to textfields without state in react/redux
我对 react/redux 有点陌生
据我所知,状态在 redux 中是不可变的,但是在搜索组件绑定示例时,我一直看到诸如
<TextField
id="usernameId"
value={this.state.username}
onChange={this.handleUsernameChange}
/>
public handleUsernameChange = (event: any) => {
this.setState({
username: event.target.value
});
}
据我所知,这是变异状态。 当我将绑定更改为使用全局变量时。 在回调中,值正在更改和更新,但是 UI 没有观察这些变量。
我想这个问题只是一个健全的检查。 这在 redux 中可以接受吗?
请注意我目前没有使用其他库
我在不使用状态的情况下尝试过的代码
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
});
}
字符串是原始类型,默认情况下它们是不可变的。
您想注意引用类型的变异对象和数组。
还行吧:
let x = 8;
x = 5; // no mutation here
这被认为是突变:
let arr = [1,2,3];
arr.push(4); // this is mutating the existing array
因此,使用引用类型,您可以创建新的对象或数组:
let arr = [1,2,3];
let arr2 = [...arr, 4]; // creating new array;
您可以使用中间件将Immutability Checkcheck添加到您的代码中:
在您的 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.