![](/img/trans.png)
[英]How can I update the React Native state if I have an array inside an object and the object is inside in a big array?
[英]Can i have a function inside a state in react?
我正在尝试在这样的状态中创建变量和函数
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()
调用它。
是的,你可以。
class App extends Component {
func1 = () => {
this.setState({flag:!this.state.flag})
}
state = {
flag:true,
doclick:this.func1
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.