Mop*_*lio 13 javascript reactjs react-native
我正在尝试在这样的状态中创建变量和函数
state = {
modalVisible: false,
photo:""
getDataSourceState
}
Run Code Online (Sandbox Code Playgroud)
我已经完成了,我如何在状态之外调用该函数并设置一个新状态。
这是我所做的,但我不断收到错误
getDataSourceState() {
return {
dataSource: this.ds.cloneWithRows(this.images),
};
}
this.setState(this.getDataSourceState());
Run Code Online (Sandbox Code Playgroud)
看看是什么促使我提出这个问题,因为我发现很难在状态中访问 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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
您不能像您尝试的那样,但从技术上讲是的,您可以拥有一个函数,该函数返回您想要在构造函数中初始化的所需状态。不过我不建议这样做。
您很快就会遇到组件未正确更新状态的问题。
您正在寻找的是一个返回值而不是设置状态的函数。你会做这样的事情:
constructor(){
super()
this.state = {
modalVisible: false,
photo:""
sourceState: this.getDataSourceState()
}
this.getDataSourceState = this.getDataSourceState.bind(this)
}
getDataSourceState(){
return this.ds.cloneWithRows(this.images)
}
Run Code Online (Sandbox Code Playgroud)
正如我所提到的,这样做不是一个好主意。您最好将状态值初始化为默认值,然后像这样在 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})
}
Run Code Online (Sandbox Code Playgroud)
这样,您就有了一个可重用的函数,componentDidUpdate()当您在具有不同数据的同一组件之间移动导航并希望更新状态时,您可以根据需要调用该函数。
| 归档时间: |
|
| 查看次数: |
16494 次 |
| 最近记录: |