【问题标题】:Global state reseting local state in React Native全局状态在 React Native 中重置本地状态
【发布时间】:2019-10-17 16:15:46
【问题描述】:

我有一个全局的 redux 状态状态对象和一个本地状态对象,用于处理组件中的 ui 内容。

问题是对 redux 状态的更改会重置我的本地/组件状态。

有什么办法可以防止吗?

我的代码

// component
constructor(props) {
    super(props);
    this.state = {
        location:5,
    }

onOtherLocationChange(text) {
    this.props.otherLocationChanged(text);
}

// in render
// the location is set to the correct value, and button is selected on click
<Button active={this.state.location === 6 ? true : false}
    onPress={() => this.setState({ location: 6 })}> // updating the local state
    <Text>LOCATION 6</Text>
</Button>
<Button active={this.state.location === 5 ? true : false}
    onPress={() => this.setState({ location: 5 })}> // updating the local state
    <Text>LOCATION 5</Text>
</Button>
<Button
    last active={this.state.location === 7 ? true : false} // updating the local state
        onPress={() => this.setState({ location: 7 })} >
    <Text>LOCATION 7</Text>
</Button>

 // text input that changes value in global state
 // this text input is displayed, but writing anything resets state back to 5
 if(this.state.location == 7) {
        return (
            <Item stackedLabel>
                <Label>Adresa mjesta rada</Label>
                <Input value={this.props.other_location} onChangeText={this.onOtherLocationChange.bind(this)} />
            </Item>
        )
    }

在文本输入中写入会触发redux状态的更新

// reducer, there is no location prop in the initial state object
...
case JOB_OTHER_LOCATION_CHANGED:
        // after this location resets back to 5
        return { ...state, other_location: action.payload, error: '' };
 default:
        return state;

动作创建者:

export const otherLocationChanged = (text) => {
    return {
       type: JOB_OTHER_LOCATION_CHANGED,
       payload: text
    };
};

【问题讨论】:

  • 你的 redux 状态不应该影响你的本地状态。请发布您的onOtherLocationChange 功能。要么那里发生了什么事,要么我也会检查你的组件是否由于某种原因正在卸载和重新安装
  • 我会添加componentWillUnmount() {console.log('unmount')} 看看会发生什么。如果我不得不猜测,我会说这就是问题所在。
  • 在你的减速器中你有一个default 的情况,返回state?我们需要更多代码来调试它。如果可以,请发布所有 reducer、组件和操作内容。
  • 我在reducer中添加了默认选项,在组件中添加了onOtherLocationChange动作创建者和事件处理程序。我还添加了componentWillUnmount,它在更改位置值时没有记录任何内容

标签: reactjs react-native redux react-redux state


【解决方案1】:

问题是 setState() 函数在 componentDidUpdate() 结束时被调用

在调用 setState 之前,我添加了一项检查以查看所需的道具是否已更新。

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 2021-01-01
    • 1970-01-01
    • 2018-05-02
    • 2019-10-15
    • 2021-11-23
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多