reactjs - 在 redux 中更新状态对象的正确方法 react native
问题描述
我做了一个函数来更新 React 中的状态,一个简单的对象。但我不确定这是否是正确的方法,因为它是不可变的。有人可以说是否正确吗?
handleInputChange = (val) =>{
// here -> some validation
this.setState({myLimit: newVal})
}
submit = () => {
let lim = {'lim':this.state.myLimit};
this.props.updateLimit(lim);
}
return (
<TextInput
keyboardType ="numeric"
autoCorrect={false}
onChangeText={ this.handleInputChange }
value={this.state.myLimit}
/>
)
const mapDispatchToProps = (dispatch) => {
return {
updateLimit: (lim) => { dispatch(updateLimit(lim))}
}
}
const mapStateToProps = (state) => {
return {
limit: state.limit,
}
}
rootReducer.js
const initState = {
expenses:[
{ key: '1', sum: '100.67'},
{ key: '2', sum: '200.00'},
],
categories: [
{ id:'1', name: 'a' },
{ id:'2', name: 'b' },
],
limit: {lim:'1000'} //<- this value I need to update
}
const rootReducer = (state = initState, action) => {
switch(action.type){
//some cases
case 'UPDATE_LIMIT': {
return {
...state,
limit: action.lim
}
}
default:
return state;
}
}
export default rootReducer;
export const updateLimit = (lim) => {
return {
type: 'UPDATE_LIMIT',
lim
}
}
它工作得很好,但我想这里可能有一些错误,因为我直接改变了状态。我将不胜感激任何帮助!
解决方案
当前实现将保存传递给操作的任何内容
const initState = {
expenses:[
{ key: '1', sum: '100.67'},
{ key: '2', sum: '200.00'},
],
categories: [
{ id:'1', name: 'a' },
{ id:'2', name: 'b' },
],
limit: {lim:'1000'} //<- this value I need to update
}
const rootReducer = (state = initState, action) => {
switch(action.type){
//some cases
case 'UPDATE_LIMIT': {
return {
...state,
limit: action.lim // <-- this will create state.limit = <value>
}
}
default:
return state;
}
}
因此,例如,如果您不小心做this.props.updateLimit(this.state.myLimit);
了而不是this.props.updateLimit({ lim: this.state.myLimit });
,则 redux 状态形状将关闭。
您可能需要调整操作以简单地采用新限制并在减速器内部处理状态形状。
注意:updateLimit
动作创建者已经接受了一个值。
const rootReducer = (state = initState, action) => {
switch(action.type){
//some cases
case 'UPDATE_LIMIT': {
return {
...state,
limit: {
lim: action.lim, // <-- create the sub-key `lim`
},
}
}
default:
return state;
}
}
现在您可以简单地发送updateLimit
您想要的新限制,即this.props.updateLimit(this.state.myLimit);
.
推荐阅读
- python - 在 lxml 中按命名空间查找
- r - 如何在从 R 中的另一个数据框计算的数据框中创建列?
- scala - map 将通过任何 String 键返回相同的值
- python - 如何基于另一个嵌套列表将缺失值附加到嵌套中?
- django - 如何在无法验证的表单字段中添加红色星号?
- reactjs - “在“Connect(ConnectedRouterWithContext)”的上下文中找不到“存储”是什么意思。意思是?
- neo4j - 将 3 个 Cypher 查询合二为一
- android-studio - 具有 API R 的 Android 模拟器无法与最新的 android studio 更新一起使用
- google-apps-script - 将 Google 脚本用于 getEditResponeURL 代码时,我可以用特定文本替换 URL 链接吗?
- javascript - 基于用户特定选项创建的输入未在 post 方法中提交