【问题标题】:Stuck While lifting state up in React Native在 React Native 中提升状态时卡住
【发布时间】:2019-01-01 11:40:30
【问题描述】:

我正在创建一个示例反应应用程序以用于学习目的,因为我遵循了不同组件的层次结构:

<RadioButton>
   //Radio buttons are rendered here and selection of radio buttons are maintained in state of this component
</RadioButton>

<SelectCard>
    <RadioButton dataToPopulate = ['choice A', 'choice B'] />
</SelectCard>

<ParentSelectCard>
    <SelectCard /> //Rendering SelectCard with passing some data as prop from here
</ParentSelectCard>

<Button />  //Custom button component

<HomeScreen>
    <ParentSelectCard />
    <Button />
</HomeScreen>

现在,当我按下按钮时,我想通过在单选按钮中传递所选选项来导航到其他屏幕。

我读过this article about lifting state up. 但问题是,这里没有我可以将状态提升到的共同父祖先。

如果我列出了&lt;HomeScreen&gt; 组件的状态,我该如何管理在&lt;RadioButton&gt; 组件中所做的选择?

这里是&lt;RadioButton&gt;组件的完整代码:

class RadioButton extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      radioSelected: 0
    }
  }

  handleRadioClick(id) {
    this.setState({
      radioSelected: id
    });
  }

  render(){
    return this.props.dataToPopulate.map((element) => {
      return (
        <View key = {element.id} style={styles.radioButton}>
          <TouchableOpacity style={styles.radioButtonTint} onPress = {this.handleRadioClick.bind(this, element.id)}>
            { element.id === this.state.radioSelected ? (<View style={styles.radioButtonSelected}/>) : (null) }
          </TouchableOpacity>
          <Text style={styles.radioButtonText}> {element.value} </Text>
        </View>
      );
    });
  }
}

这里可以看到最终做出的选择会保存在这个组件的状态中(radioSelected)。

我在这里缺少什么?我的&lt;RadioButton&gt;设计错了吗?

【问题讨论】:

  • 就个人而言,我会选择 redux 或 mobx 或其他状态管理库来存储全局状态。
  • 所以 redux 是用于将状态存储到某个全局变量,然后从任何地方访问它,对吗?我是 React/Redux 的新手。
  • 是的,没错。通常你会有容器组件来访问 redux 存储并选择状态的特定部分,然后将其传递给 ui 组件。本课程是免费的,可能会帮助您入门:egghead.io/courses/getting-started-with-redux

标签: javascript reactjs react-native ecmascript-6 react-state-management


【解决方案1】:

我在这里缺少什么?难道我的设计错了吗?

如果你“提升状态”,单选按钮本身不应该有任何状态。而是将处理程序传递给 RadioButton:

 <RadioButton onChange={value => this.doSomethingWith(value)} />

然后,您可以在单选按钮内部调用它,无论何时发生更改,并在&lt;App/&gt; 中处理结果。

如果您必须通过多个级别传递该处理程序,最好使用context

【讨论】:

  • 你能举一个例子或任何相关的链接来解释传递处理程序吗?感谢您的回答。
  • @kaushal28 它在您链接的官方反应文档中:)
  • 无法通过传递处理函数使其工作。有这样的例子吗?
  • 知道了!这是示例:stackoverflow.com/questions/35537229/…。感谢您提出正确的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多