[英]React Component does not render after the state changes
您好,我在重新渲染下面的組件時遇到問題,您可以在第一個屏幕中看到我的代碼,其中我有一個自定義組件:
class Ahelle extends React.Component{
constructor(props){
super(props)
this.state={
mamad:10
}
}
render(){
return (
<View style={{backgroundColor:"white"}}>
<ScrollView>
<CustomSlider defaultValue={0} />
<CustomSlider defaultValue={this.state.mamad} disabled={true}/>
<TouchableOpacity style={{width:100,height:100,alignSelf:"center"}} onPress={()=>{this.setState({mamad:20})}}><Text>dddd</Text></TouchableOpacity>
</ScrollView>
</View>
);
}
}
這里我有一個自定義組件,我傳遞了一個默認值來顯示,但是當我更改 state 時,它不會更改我作為道具傳遞的值。 這是我的自定義 slider 組件及其 state、道具和任何其他細節。
class Test extends React.Component{
constructor(props){
console.log(props)
super(props)
this.state = {
value: props.defaultValue
};
}
render(){
return(
<Slider
style={{width: wp("70%")}}
value={this.state.value}
/>
)
}
}
export default Test;
查看實際問題感謝您抽出寶貴時間
您的 slider 組件永遠不會對傳遞的更新的 prop 值執行任何操作。 巧合的是,將傳遞的道具存儲在本地組件 state 中也是一種反應反模式。 您可以而且應該直接食用它們。 只需將this.state.mamad
傳遞給value
道具並使用即可。 您還可以通過將任何其他道具傳播到 slider 組件來傳遞它們。
class Test extends React.Component {
render() {
return (
<Slider
style={{ width: wp("70%") }}
value={this.props.value}
{...this.props}
/>
);
}
}
export default Test;
用法
<CustomSlider value={this.state.mamad} disabled={true} />
如果你真的想存儲傳遞的defaultValue
並保持更新,那么實現componentDidUpdate
生命周期 function。 請注意,這不是推薦的解決方案。
class Test extends React.Component {
constructor(props) {
console.log(props);
super(props);
this.state = {
value: props.defaultValue
};
}
componentDidUpdate(prevProps) {
const { defaultValue } = this.props;
if (prevProps.defaultValue !== defaultValue) {
this.setState({ value: defaultValue});
}
}
render() {
return <Slider style={{ width: wp("70%") }} value={this.state.value} />;
}
}
export default Test;
你的代碼是正確的。 我測試了它。
應用程序.js
import React from "react";
import { Text, View, ScrollView, TouchableOpacity } from "react-native";
import CustomSlider from "./CustomSlider";
export default class Ahelle extends React.Component {
constructor(props) {
super(props);
this.state = {
mamad: 10,
};
}
render() {
return (
<View style={{ backgroundColor: "white" }}>
<ScrollView>
<CustomSlider defaultValue={0} />
<CustomSlider defaultValue={this.state.mamad} disabled={true} />
<TouchableOpacity
style={{ width: 100, height: 100, alignSelf: "center" }}
onPress={() => {
this.setState({ mamad: 20 });
}}
>
<Text>dddd</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
}
CustomSlider.js
import React from "react";
import { Text } from "react-native";
export default class CustomSlider extends React.Component {
render() {
return <Text>defaultValue: {this.props.defaultValue}</Text>;
}
}
結果:查看結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.