Can i have a function inside a state in react?

后端 未结 2 1127
面向向阳花
面向向阳花 2021-01-17 12:23

I\'m trying to create variables and a function inside a state like this

     state = {
          modalVisible: false,
          photo:""
          g         


        
2条回答
  •  情歌与酒
    2021-01-17 13:07

    You can't the way you have attempted but technically yes, you can have a function that returns the desired state you want initialised in your constructor. I wouldn't suggest doing it though.

    You will quickly run into issues where your components aren't updating state correctly.

    What you are looking for is a function that returns a value as opposed to sets state. You would do something like this:

    constructor(){
      super()
    
      this.state = {
        modalVisible: false,
        photo:""
        sourceState: this.getDataSourceState()
      }
    
      this.getDataSourceState = this.getDataSourceState.bind(this)
    }
    
    getDataSourceState(){
      return this.ds.cloneWithRows(this.images)
    }
    

    As I mentioned, it is not a good idea to do it this way. You are better off initialising the state values as a default value and then setting the state in your componentDidMount like so:

    constructor(){
        super()
    
        this.state = {
            modalVisible: false,
            photo:""
            sourceState: null
        }
    
        this.getDataSourceState = this.getDataSourceState.bind(this)
    }
    
    
    componentDidMount(){
        this.getDataSourceState()
    }
    
    getDataSourceState(){
    
        const data = this.ds.cloneWithRows(this.images)
    
        this.setState({soureState: data})
        
    }
    

    This way you have a reusable function which you can call in componentDidUpdate() if need be for when you move navigate between the same component with different data and want the state to update.

提交回复
热议问题