我的React Native项目中有一个sectionList。如果项目更改,它不会重新渲染。 我的代码:
test.js
class Test extends React.Component {
started = false;
causeData=[];
showLess=false;
items = [];
_start = () => {
const { ws } = this.props;
this.showLess = false;
if (ws.causes.length) {
this.causeData = {
title: Language.causes,
key: "cause",
data: []
};
ws.causes.forEach(cause => {
let causeDetails = {
key: "cause_" + cause.id,
name: "",
value: cause.name,
sortIndex: cause.sortIndex,
progress: cause.progress
};
this.causeData.data.push(causeDetails);
if (this.causeData.data.length > 4) {
this.causeData.data = this.causeData.data.slice(0, 4);
}
});
this.items.push(this.causeData);
console.log("causeData", this.causeData);
}
}
}
_renderItem = ({ item }) => {
return (
<View>
<Text key={item.key} style={styles.text}>{`${item.name} ${
item.value
}`}</Text>
</View>
);
};
_renderSectionHeader = ({ section }) => {
const { ws } = this.props;
const showMore = ws.causes.length > 0 && !this.showLess;
return (
<View style={styles.sectionHeader}>
<Text key={section.key} style={styles.header}>
{section.title}
</Text>
{showMore && (
<Button
onPress={this._afterCauseAnswered}
title={Language.showMore}
data={this.items}
accessibilityLabel={Language.causeDoneAccessibility}
/>
)}
</View>
);
};
_keyExtractor = (item, index) => item.key;
_afterCauseAnswered = () => {
const { stepDone, ws } = this.props;
this.causeData.data = { ...ws.causes };
stepDone("showMoreAnswered");
this.showLess = true;
};
render = () => {
if (!this.started) {
this.started = true;
this._start();
}
return (
<View style={styles.container}>
<SectionList
sections={this.items}
extraData={this.items}
renderItem={this._renderItem}
renderSectionHeader={this._renderSectionHeader}
keyExtractor={this._keyExtractor}
/>
</View>
);
};
}
在我的部分列表的部分标题中包含一个名为showMore的按钮。在初始渲染时,它将仅显示5个项目,而单击showMore时,它将显示所有列表。这是我的功能。但是在单击showMore按钮时,它不会显示整个列表,仅显示5个项目,这意味着sectionList不会重新呈现。如何解决呢?我是新来的本地人。知道我想念什么吗?任何帮助将不胜感激!
答案 0 :(得分:1)
保持items
和showLess
的状态,并在按下按钮后用新值调用setState
。它将重新呈现SectionList
。另外,如果要显示带有显示列表的多个项目,则需要将showLess
移动到item元素,以便每个项目都知道如何显示它。
答案 1 :(得分:0)
您只需要使用状态重新渲染屏幕即可,
this.setState({})
答案 2 :(得分:0)
您的SectionList
应该始终从state
阅读,因为它应该是您的单一事实来源
方法如下:
class YourComponent extends React.Component {
state = {
items: [],
};
// This will be called after your action is executed,
// and your component is about to receive a new set of causes...
componentWillReceiveProps(nextProps) {
const {
ws: { causes: nextCauses },
} = nextProps;
if (newCauses) {
// let items = ...
// update yout items here
this.setState({ items });
}
}
}