【问题标题】:How to setState() depend on which component func is called?如何 setState() 取决于调用哪个组件函数?
【发布时间】:2019-01-21 03:22:06
【问题描述】:

我想根据调用的函数设置动态状态,我知道我们是否不能在渲染中setstate,但我仍然需要这样做来设置动态状态,

有什么方法可以实现吗?

export default class Foo extends Component {
  constructor(props) {
    super(props);
    this.state={
      dynamicView:false
    }
  }
  renderText(key, value){
    this.setState({[key]:value})
    <Text>Simple render</Text>
  }
  renderButton(key, value){
    this.setState({[key]:value})
    <Text>Simple render</Text>
  }
  render(){
    return(
      <View>
        {this.state.dynamicView ? this.renderButton("button","ValueButton") : this.renderText("text", "valueText")}
        <Button
          title="change Component"
          onPress={()=>this.setState({dynamicView:!this.state.dynamicView})}
        />
        <Button
          title="Isi State"
          onPress={()=>alert(JSON.stringify(this.state,null,4))}
        />
      </View>
    )
  }
}

使用这些代码我可以设置动态状态,但问题是在调用 component function 时,我有两个状态 (button and text),我想避免这种情况,所以我只有 1 个状态 (button / text) 取决于显示哪个组件,

我该怎么做?

注意:这只是一个简单的用例,我只需要知道设置状态取决于调用哪个函数

【问题讨论】:

    标签: android react-native setstate


    【解决方案1】:

    如果您只想保留按钮或文本状态,那么您应该考虑更改其他状态。

        renderText(key, value){
        this.setState({[key]:value})
        this.setState({button:false})
        <Text>Simple render</Text>
      }
    

    【讨论】:

    • 如果你这样做,状态仍然有 2 个键
    • 如果你想减少状态键,那么这是另一个问题。在这种情况下,可以仅根据一个键来呈现视图。 但问题是显示任一组件功能,我认为我的回答解决了这个问题。
    • 正如你在我的帖子中看到的,我想避免这种情况
    【解决方案2】:

    我认为您需要在状态中添加另一个变量,并根据 dynamicView 的条件触发的函数对其进行更新。

    export default class Foo extends Component {
      constructor(props) {
      super(props);
       this.state={
         dynamicView:false,
         viewType:''
       }
     }
      renderText(viewType){
        this.setState(viewType)
        <Text>Simple render</Text>
      }
    
     renderButton(viewType){
       this.setState({viewType})
       <Text>Simple render</Text>
      }
    
     render(){
       return(
        <View>
         {this.state.dynamicView ? this.renderButton("button","ValueButton") : 
          this.renderText("text", "valueText")}
          <Button
           title="change Component"
           onPress={()=>this.setState({dynamicView:!this.state.dynamicView})}
           />
          <Button
           title="Isi State"
           onPress={()=>alert(JSON.stringify(this.state,null,4))}
          />
       </View>
      )
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多