Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native 可以在构造函数中设置state吗?_React Native - Fatal编程技术网

React native 可以在构造函数中设置state吗?

React native 可以在构造函数中设置state吗?,react-native,React Native,我试图在构造函数中设置state,但不知为什么它不起作用 constructor(props) { super(props); this.state = { example: false } this.setState({example: true}) //Not doing anything } 这也不起作用: constructor(props) { super(props); this.state = { example: false } this.stat

我试图在构造函数中设置state,但不知为什么它不起作用

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函数中处理PanResponder吗?是的,我可以试试,谢谢我试过了,但它不起作用。不知何故,setState仍然无法填充它。请您解释一下为什么需要它?我已经编辑了我的问题,您不能改为在componentDidMount函数中处理PanResponder吗?是的,我可以尝试,谢谢我尝试过,但它不起作用。不知怎的,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
  }