我当时正在使用大学提供的代码进行练习,但是现在抛出了错误消息“不变违反:文本字符串必须在文本组件中呈现”我什至完全制作了一个新文件来使用原始代码,但仍然会收到该错误。
为什么有这种突然发生的原因,请问如何解决?
谢谢
import React from 'react';
import { StyleSheet, FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props) {
super(props);
this.state = { isLoading: true }
}
componentWillMount () {
const localMovieData = require('./assets/test.json');
this.setState({
isLoading: false,
dataSource: localMovieData.movies,
}, function () {
});
}
_renderItem = (info) => {
return <Text>{this.state.dataSource.map((movie, index) => (
<p>Hello, {movie.title} from {movie.releaseYear}!</p>
))}</Text>
}
render() {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
keyExtractor={({ id }, index) => id}
/>
</View>
);
}
}
JSON数据
{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "id": "1", "title": "Star Wars", "releaseYear": "1977" },
{ "id": "2", "title": "Back to the Future", "releaseYear": "1985" },
{ "id": "3", "title": "The Matrix", "releaseYear": "1999" },
{ "id": "4", "title": "Inception", "releaseYear": "2010" },
{ "id": "5", "title": "Interstellar", "releaseYear": "2014" }
]
}
答案 0 :(得分:0)
尝试一下...
建议使用componentDidMount
进行api调用,因为componentWillMount
已过时。 reference
代码- 您可以像这样导入
import data from './test.json';
export default class App extends React.Component {
state={
dataSource:data
}
_renderItem = (info) => {
return <Text>{this.state.dataSource.map((movie, index) => (
<Text>Hello, {movie.title} from {movie.releaseYear}</Text>
))}</Text>
}
render() {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
keyExtractor={({ id }, index) => id}
/>
</View>
);
}
}