React Native中的全局状态重置本地状态

问题描述 投票:0回答:1

我既有全局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
    };
};
reactjs react-native redux react-redux state
1个回答
0
投票

问题是setState()函数在componentDidUpdate()的末尾被调用

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

© www.soinside.com 2019 - 2024. All rights reserved.