setState无效



  • setState无效?为什么。
    代码如下,num一直还是3,不是后来设置的2.这是为啥?

    constructor(props){
    super(props);
    this.state = {
    data:null,
    num:3,
    };
    }

    componentDidMount () {
        this.getDataProvider();
    };
    
    render() {
        if(!this.state.data){
            return(
                <Text>loading...{this.state.num}</Text>
            )
        } else {
            return (
                <View style={styles.container}>
                    <ListView style={{flex: 1}} automaticallyAdjustContentInsets={false}
                              dataSource={this.state.data}
                              renderRow={(rowData, sectionID, rowID) => this._renderRowCell(rowData, sectionID, rowID)}
                    />
                </View>
            );
        }
    }
    
    getDataProvider(){
        //POST方式
        let params = {"iOSApiVersion": "iOS_1.1.1", "iOSAppVersion": "2.1.4(2.1.6)"};
        fetch("https://www.toolmall.com/app/productcategory/iosroots_v2.jhtm", {
            method: "POST",
            mode: "cors",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: JSON.stringify(params),
        })
            .then(function (res) {
            console.log("fetch request ", JSON.stringify(res.ok));
            if (res.ok) {
                res.json().then(function (json) {
                    console.info(json);
                    Alert.alert(json.data[0].name);
                    () => this.setState({
                        // data:new ListView.DataSource({rowHasChanged:(r1,r2)=> r1 !== r2}).cloneWithRows(json.data),
                        num:222,
                    });
    
                });
            } else {
                Alert.alert('访问失败');
            }
    
        }).catch(function (e) {
            console.log("fetch fail");
            Alert.alert('提示', '系统错误', [{text: '确定', onPress: () => console.log('OK Pressed!')},]);
        });
    };

  • administrators


登录后回复