我可以在状态内有一个功能吗?

时间:2018-03-27 10:52:15

标签: javascript reactjs react-native

尝试在像这样的状态中创建变量和函数

     state = {
          modalVisible: false,
          photo:""
          getDataSourceState
    }

我已经完成了,如何在州外调用该函数并设置一个新状态。

这就是我所做的但是我一直在犯错误

    getDataSourceState() {
        return {
          dataSource: this.ds.cloneWithRows(this.images),
        };
      }



    this.setState(this.getDataSourceState());

看看是什么促使我问这个问题,因为我发现很难在状态中访问modalVisible,因为有一个this.state = this.getDataSource()

constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      photo:"",
      sourceState: getDataSourceState()
    }
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.lastPhotoFetched = undefined;
    this.images = [];
    this.fetchPhotos();
    this.getDataSourceState = this.getDataSourceState.bind(this)
  }

componentDidMount(){
  this.getDataSourceState();
}

  getDataSourceState() {
    return {
      dataSource: this.ds.cloneWithRows(this.images),
    };
  }

  getPhotosFromCameraRollData(data) {
    return data.edges.map((asset) => {
      return asset.node.image;
    });
  }

}

2 个答案:

答案 0 :(得分:1)

您可以按照尝试的方式进行操作,但从技术上讲,您可以使用一个函数返回您想要在构造函数中初始化的所需状态。我不建议这样做。

您将很快遇到组件未正确更新状态的问题。

您正在寻找的是一个返回值而不是设置状态的函数。你会做这样的事情:

constructor(){
  super()

  this.state = {
    modalVisible: false,
    photo:""
    sourceState: this.getDataSourceState()
  }

  this.getDataSourceState = this.getDataSourceState.bind(this)
}

getDataSourceState(){
  return this.ds.cloneWithRows(this.images)
}

正如我所提到的,这样做并不是一个好主意。最好将状态值初始化为默认值,然后在componentDidMount中设置状态,如下所示:

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})

}

通过这种方式,您可以在componentDidUpdate()中调用可重用的函数,如果您需要在具有不同数据的同一组件之间导航并希望状态更新时可以调用。

答案 1 :(得分:0)

是的。

class App extends Component {
    func1 = () => {
        this.setState({flag:!this.state.flag})
    }
   state = {
       flag:true,       
       doclick:this.func1
    }
} 
相关问题