我试图在这样的状态下创建变量和函数

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

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

这就是我所做的,但我不断出错

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



    this.setState(this.getDataSourceState());

看看是什么促使我问这个问题,因为我发现在这个州很难访问modalVisible,因为有一个这样的问题.州=这个.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;
    });
  }

}

推荐答案

你不能像你try 的那样,但是从技术上来说,你可以有一个函数,返回你想要在构造函数中初始化的状态.不过我不建议你这么做.

您将很快遇到组件无法正确更新状态的问题.

你要找的是一个函数,它返回一个值,而不是集合状态.你可以这样做:

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()中调用该函数.

React-native相关问答推荐

'无法解析模块.安装react-native-pager-view后的实用程序/平台

如何在使用嵌套的堆栈导航器在选项卡之间导航后弹出到堆栈顶部?

莫迪德不会停留在屏幕中央

嵌套的FlatList内的Incorrect Padding

在 React Native 中,水平滚动不适用于我的整个应用程序

找不到变量 atob

react-native (expo)加载markdown 文件

React Native 转换与枢轴点

你如何在生产模式下运行 react-native 应用程序?

submit提交后如何让 React Native TextInput 保持焦点?

Xcode 12 问题:Build input file cannot be found

错误: Unable to determine the current character, it is not a string, number, array, or object in react-native for android

Xcode 设备不可用,未找到运行时配置文件

在关闭 react-native 时更改 Switch 的 colored颜色

react-native图标

如何将 Tensorflow 与 react-native 一起使用?

如何在 react-native 中重叠

react-native:0.41 app.json

React Native - 为什么我需要 babel 或 webpack?

如何将图形 API 与 react-native-fbsdk 一起使用?