Value for message cannot be cast from ReadableNativeMap to String的解决方案

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/HermitSun/article/details/101395470

这是在React Native文档里看到的例子:

componentDidMount(){
    return fetch('https://facebook.github.io/react-native/movies.json')
        .then((response) => response.json())
        .then((responseJson) => {
        	this.setState({
                isLoading: false,
                dataSource: responseJson.movies,
            });
    	})
        .catch((error) =>{
        	console.error(error);
    	});
}

首先声明,这段代码是没有错误的。但是我在写的时候,出现了红屏:

Can't solve Fatal Exception:Value for message cannot be cast from ReadableNativeMap to String

回去查代码,发现是少写了括号,把response.json()写成了response.json。但是为什么会是这个报错呢?而且这个报错对于解决问题也没有任何帮助啊。这个问题可能只有等深入了解了才能知道吧。

另外,因为RN可以和其他基于XMLHttpRequest的网络请求库兼容,所以我选择axios,就没有JSON转换的问题了(

此外,如果用了eslint(并且用了@react-native-community的扩展规则),这段代码其实会有warning,提示如下:

Do not use setState in componentDidMounteslint(react/no-did-mount-set-state)

仔细想想就能明白,mount的时候页面已经完成了渲染,在这个时候setState会触发重绘,显然是不正确的;为什么不移到constructor里去呢?

但是移到constructor里之后又会有一个新的问题:constructor是不能写成async函数的。所以……还是得回退到Promise。

猜你喜欢

转载自blog.csdn.net/HermitSun/article/details/101395470
今日推荐