草庐IT

javascript - react native + 终极版 : Why does Switch immediately turns back to false after being switched to true?

coder 2024-07-25 原文

在 iOS React Native + Redux 中,我使用了以下 Switch 组件 ( https://facebook.github.io/react-native/docs/switch.html )。它首先设置为关闭,但是当打开时,它会立即自行关闭。可能是什么问题?

这是我的设置:

<Switch
  onValueChange={this._handleSwitch}
  value={switch.currentValue}
/>

触发的 Action 是:

  _handleSwitch(value) {
    this.props.actions.triggerSwitch(value)
  }

Action 是:

export function triggerSwitch(value) {
  return {
    type: TRIGGER_SWITCH,
    currentValue: value
  }
}

在 reducer 中:

const initialState = {
  currentValue: false
}

function switchReducer(switch = initialState, action) {
  switch(action.type) {
    case TRIGGER_SWITCH:
      return {
        currentValue: action.currentValue
      }

     default:
       return switch
  }
}

export default switchReducer

谢谢!

最佳答案

这不是因为 redux,要使 Switch 工作,我们需要从状态中显式设置 value,否则会设置回 false 立即

<Switch
  value={this.state.hasRead}
  onValueChange={(value) => {
    this.setState({
      hasRead: value
    })
}} />

关于javascript - react native + 终极版 : Why does Switch immediately turns back to false after being switched to true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39222579/

有关javascript - react native + 终极版 : Why does Switch immediately turns back to false after being switched to true?的更多相关文章

随机推荐