问题
I'm getting an error at dataSource: responseJson.event_array
, when I remove this line everything works fine however, when I compare it to other peoples code it's the same. It does reach the server, because I do not get the alert message.
componentDidMount() {
fetch('valid url')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.event_array,
isLoading: false
});
})
.catch((error) => {
alert('Could not reach the server!')
});
}
What am I doing wrong, The error is
Invariant Violation: Objects are not valid as a React child (found: object with keys {_40,_65,_55,_72})
'valid url' points to a json file and is indeed an object, I'm trying to use the data to compare it to other data stored to use a if function wich will decide wether the item of FlatList will be rendered or not
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
keyExtractor={item => item.name}
/>
another piece of code
renderItem = async ({item}) => {
var approved = false;
var name_string = await AsyncStorage.getItem('planner_name');
if(name_string != null){
var name_array = name_string.split(',');
name_array.map(name => {
if(name == item.name){
approved = true;
}
})
}
startReading = ({item}) => {
this.setState({
reading: true,
item: item
});
}
if(approved){
return (
<TouchableOpacity style={{flex: 1, flexDirection: 'row', marginBottom: 5}} onPress={() => this.startReading({item})}>
<Text>{item.name}</Text>
</TouchableOpacity>
);
} else {
return null
}
}
If you have any question feel free to ask. Thank you for your time.
回答1:
This:
object with keys {_40,_65,_55,_72}
is an unresolved promise. I suspect the issue is that this.renderItem
is an async
function which I suspect is not allowed. async
is essentially going to wrap the result of your function in a Promise
, which then must be resolved. Since renderItem
does not expect a Promise
, it does not know to resolve one and as such is simply returning an unresolved Promise
object for each item in your data source.
Instead you could try using an async
function expression:
renderItem = ({item}) => {
const get_name_string = async function(key){
const name_string = await AsyncStorage.getItem('key')
return name_string
}
get_name_string('planner_name').then(name => {
// the rest of your renderItem function should be in this block
})
}
or simply using .then
syntax on the call to AsyncStorage
renderItem = ({item}) => {
AsyncStorage.getItem('planner_name').then(name => {
// again, the rest of your function should be in this block
})
}
or better yet find another pattern that doesn't require you to use asynchronous code in your renderItem
function. Hope this helps, let me know if you have any questions!
来源:https://stackoverflow.com/questions/53325386/react-native-objects-are-not-valid-as-a-react-child