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

时间:2019-10-17 16:15:46

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

我既有全局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
    };
};

1 个答案:

答案 0 :(得分:0)

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

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