gpt4 book ai didi

javascript - 我可以在 react 状态中有一个功能吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:10:32 24 4
gpt4 key购买 nike

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

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

}

最佳答案

你不能像你尝试的那样,但从技术上讲是的,你可以有一个函数返回你想要在你的构造函数中初始化的所需状态。不过我不建议这样做。

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

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

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() 中调用它,如果需要的话,当你在具有不同数据的相同组件之间移动导航并希望更新状态时。

关于javascript - 我可以在 react 状态中有一个功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49510990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com