我试图在构造函数中设置setState但不知何故它不起作用。
constructor(props) {
super(props);
this.state = {
example: false
}
this.setState({example: true}) //Not doing anything
}
这两项都不起作用:
constructor(props) {
super(props);
this.state = {
example: false
}
this.state.example = true //Not doing anything
}
我的理由是:
constructor(props) {
super(props);
this.state = {
panResponders: []
}
let panResponders = []
for(let i=0; i < 5; i++){
panResponders.push(this.panResponder(i), this.state.showDraggable)
}
this.setState({panResponders: panResponders}) //I want to do this
}
我希望以后能够在构造函数中将状态添加到状态
修改
我在componentDidMount中尝试过第一个console.log()
是一个数组但是setState()
没有对它进行处理它还是空的。
componentDidMount(){
const {question, actions} = this.props
this.panResponder = (number, draggables) => PanResponder.create({
onStartShouldSetPanResponder : () => true,
onPanResponderMove : Animated.event([null,{
dx : this.state.pan[number].x,
dy : this.state.pan[number].y
}]),
onPanResponderRelease : (e, gesture) => {
if(this.isDropZone(gesture)){
this.setState({
showDraggable : draggables
});
}else{
Animated.spring(
this.state.pan[number],
{toValue:{x:0,y:0}}
).start();
}
}
});
let panResponders = []
for(let i=0; i < question.currentQuestion.antwoorden.length; i++){
panResponders.push(this.panResponder(i), this.state.showDraggable)
}
console.log(panResponders) //Populated array
console.log(this.state.panResponders) // null
this.setState({panResponders: "panResponders"})
console.log(this.state.panResponders) // null
}