我正在我的 React Native 应用程序中实现一个单词搜索工具。我有一个 MobX 商店,wordStore
。每个文本更改都会通过 setFilter
操作触发数据库查询。正如我从控制台调试输出中看到的那样,这一切都在幕后工作。
但是,一旦触发任何更新,WordList
组件似乎就会消失,即,如果我设置默认过滤器字符串,它会显示列表中的匹配项目,但一旦任何文本发生更改,它就会立即消失消失。
有什么我想念的吗?奇怪的是 WordList.render()
方法即使不可见也会执行。
编辑: 渲染数组的 .toString()
方法在包含组件中工作正常,但奇怪的是迭代数组也显示相同的行为,在更新时消失。
包含组件:
const WordSearch = observer(class WordSearch extends React.Component {
constructor(props) {
super(props);
}
render() {
let words = wordStore.getWords(); // For debugging
return (
<View>
<TextInput
style={styles.textInput}
onChangeText={(filter) => wordStore.setFilter (filter)}
value={wordStore.filter}
/>
<Text>{words.toString()}</Text> <!-- This works -->
<View style={{flex:1}} key={wordStore.filter}> <!-- This disappears too -->
{words.map((word, i) => {
console.log ('word: '+word);
return <View style={{flex:1}} key={i}>
<Text>{word}</Text>
</View>
})}
</View>
<WordList {...this.props} />
</View>
);
}
// ...
});
和 WordList 组件:
const WordList = observer(class WordList extends Component {
constructor(props) {
super(props);
this.dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
})
}
componentWillReact() {
console.log("I will re-render, since the words have changed!");
}
componentWillUpdate() {
console.log("Will update")
let words = wordStore.getWords();
this.dataSource = this.dataSource.cloneWithRows(words);
console.log ("words:");
console.log (words);
}
render() {
return (
<View style={styles.container}>
<ListView
key={wordStore.words}
dataSource={this.dataSource}
renderRow={this.renderWordRow}
style={styles.listView}
/>
</View>
)
}
renderWordRow = (word, sectionID, rowID) => {
console.log ('rendering word row: '+word)
return (
<TouchableHighlight
underlayColor="grey">
<View style={styles.rowContainer}>
<Text style={styles.title}>{word}</Text>
</View>
</TouchableHighlight>
);
}
});
export default WordList;
最佳答案
这是一个愚蠢的错误。这是因为未在包含 View 中设置 flex
。上面例子的正确代码:
<View style={{flex:1}}>
<TextInput
style={styles.textInput}
onChangeText={(filter) => wordStore.setFilter (filter)}
value={wordStore.filter}
/>
<WordList {...this.props} />
</View>
关于javascript - 组件在更新时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44473192/