我有一个与计数器关联的图像,并且基于计数器的这种增量或减量,计算完成并显示在底部的文本中。
问题在于,当我渲染时,图像会再次渲染并一次又一次地加载。我不想要。
如果我不渲染,则文本将不会以计算出的数量更新。 对于计数器,我使用了react-native-counter。
我已经尝试过shouldcomponentupdate,但是我只想停止图像渲染,其余的都应该工作。
请告知。
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Header
backgroundColor="#25D366"
leftComponent={
<Icon
name="menu"
size={40}
color={"#fff000"}
onPress={() => this.props.navigation.openDrawer()}
/>
}
centerComponent={{
text: "Veg & Fruits",
style: {
color: "#ffffff",
fontSize: 25,
fontWeight: "bold",
},
}}
rightComponent={<Icon name="home" color={"#ff0000"} />}
></Header>
/// this is searchbar component,
<SearchBar
fontColor="#ffffff"
fontWeight="bold"
fontSize={20}
iconColor="#c6c6c6"
shadowColor="#ffffff"
cancelIconColor="#c6c6c6"
backgroundColor="#25D366"
placeholder="Search here"
onChangeText={(text) => {
this.setState({ photos: [] });
this.state.search = text;
this.filterList(this.state.search);
console.log("text changed");
}}
onPressCancel={(text) => {
text = "";
//this.filterList(text);
}}
onPress={(text) => {
console.log("rendering");
console.log("now text is: ", this.state.search);
}}
/>
/// in this view images are displayed using functions
<View>
<ScrollView
style={{
height: Dimensions.get("window").height - 200,
}}
>
<View
key={Date.now()}
style={{
flex: 1,
flexDirection: "column",
flexWrap: "wrap",
}}
>
{this.filterList(this.state.search)}
{this._renderImages()}
</View>
</ScrollView>
<CalcText tt={total_num} />
</View>
</div>
);
}
}
class CalcText extends Component {
constructor(props) {
super(props);
this.state = {
ta: 0,
};
}
shouldComponentUpdate(nextProps) {
console.log(nextProps.tt);
if (this.props.tt !== nextProps.tt) {
console.log("changed");
return true;
} else {
console.log("Not changed");
return false;
}
}
render() {
return (
<View style={{ height: 40, backgroundcolor: "ff0000" }}>
<Text style={{ fontSize: 26, fontWeight: "bold" }}>
Total : {this.props.tt}
</Text>
</View>
);
}
}
答案 0 :(得分:0)
您可以创建一个TextBox
组件并将其与ImageComponent
分开。这样,图像将不会绑定到组件渲染文本的状态,并且您可以安全地更改TextBox
的状态和文本,从而防止ImageComponent
重新渲染。
编辑:
Okei,现在我明白了。我认为您不可能这样做。
让我们正式化这个问题:
<Parent>
<Images calc={functionToCalc} />
<CalcText totalAmount={this.state.totalAmount}/>
</Parent>
functionToCalc
在<Parent>
中定义,并更新父状态,例如:
const funcToCalc = () => {
// when condition occurs
this.setState({
totalAmount : computedAmount
})
}
<Parent>
的状态为:
this.state : {
totalAmount: none
}
只要在<Images/>
中发生情况(buttonClick?),您就会运行functionToCalc
更新<Parent>
状态并重新呈现<CalcText>
。这里的问题是<Images>
也将被重新渲染,因为所有父组件都将被重新渲染。
这是从React中的兄弟姐妹传递信息的一种方式。
只有当您想阻止<Images>
重新呈现时,您才有可能。
您将把计算的计算结果移到Store
中,而<CalcText/>
将从那里读取。 <Images/>
组件将触发修改该状态的操作,但不会监听该状态,因此不会被重新渲染。