问题描述
我在 DrawerNavigator 下有这个屏幕:
I have this screen under a DrawerNavigator:
class myScreen extends Component {
state: Object;
constructor(props) {
super(props);
this.getBeers();
this.state = {
is_loading: true,
beers: null,
beers_ds: null,
}
}
componentWillUpdate(nextProps: Object, nextState: Object)
{
if(!nextState.is_loading)
{
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
nextState.beers_ds = ds.cloneWithRows(nextState.beers);
}
}
async getBeers()
{
let finalApiURL = API_BASE_URL;
let fetchResult = await fetch(finalApiURL)
let Result = await fetchResult.json();
this.setState({users: Result, is_loading: false});
}
render()
{
if(this.state.is_loading)
{
return(
<View style={{ flex: 1, backgroundColor: 'white', marginTop: 50 }}>
<Text>
Loading ...
</Text>
</View>
)
}
else
{
let renderRow = (row) => {
return (
<TouchableOpacity onPress={ () => {} }>
<View >
<Text>{row.name}</Text>
<Text style={{ color: 'blue' }}>ADD</Text>
</View>
</TouchableOpacity>
);
}
return
(
<View >
<ListView dataSource={this.state.beers_ds} renderRow={renderRow.bind(this)} />
</View>
);
}
}
}
export default myScreen;
现在当我从服务器得到结果时,我setState()
.然后,componentWillUpdate()
被调用,并且 render()
中的 else()
语句被触发.
Now when I get results back from the server, I setState()
. Then, componentWillUpdate()
gets called, and the else()
statement in render()
fires.
但我的屏幕没有改变,它一直在Loading ..
.
But my screen does not change and it stays on Loading ..
.
有时我会看到这个错误:
And sometimes I get see this error:
谁能帮忙找出为什么会发生这种奇怪的行为?
Can anyone help in finding why this weird behavior is occurring?
谢谢
当我改变它时它会起作用:
It works when I change this:
return
(
为此:
return (
欢迎使用 JavaScript!
Welcome to Javascript!
推荐答案
我会假设你有最新的 react native
所以 ListView
被弃用你可以使用 FlatList
(Dod) 代替
I will assume that you have the latest react native
so ListView
is deprecated you can use FlatList
(Dod) instead
把你的代码改成这样
renderRow = (row) => {
return (
<TouchableOpacity onPress={ () => {} }>
<View >
<Text>{row.name}</Text>
<Text style={{ color: 'blue' }}>ADD</Text>
</View>
</TouchableOpacity>
);
}
render() {
return(
<View style={{ flex: 1, backgroundColor: 'white', marginTop: 50 }}>
{this.state.is_loading ?
<Text>
Loading ...
</Text>
:
<FlatList data={this.state.users} renderItem={(item) => this.renderRow(item)} />
}
</View>
);
}
这篇关于setState 触发并且渲染方法被命中,但没有重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!