Javascript 反应本机组件不';状态更改时不重新渲染
无论我尝试什么,我似乎都无法更新我的组件。下面是我的代码:Javascript 反应本机组件不';状态更改时不重新渲染,javascript,react-native,react-native-android,Javascript,React Native,React Native Android,无论我尝试什么,我似乎都无法更新我的组件。下面是我的代码: import React, { Component } from "react"; import { StyleSheet, View, TouchableOpacity, Image, Text } from "react-native"; import PropTypes from "prop-types"; import { toggleSound } from "logic/Music.js"; import soundOn
import React, { Component } from "react";
import { StyleSheet, View, TouchableOpacity, Image, Text } from "react-native";
import PropTypes from "prop-types";
import { toggleSound } from "logic/Music.js";
import soundOn from "assets/img/swipe.png";
import soundOff from "assets/img/illum-triangle.png";
export default class GlobalSoundButton extends Component {
constructor(props) {
super(props);
this.state = {
audioOff: this.props.audioOff
};
}
componentDidUpdate = prevProps => {
if (prevProps.audioOff !== this.props.audioOff) {
this.setState({ audioOff: this.props.audioOff }, () => {
console.log("SWITCHING STATE", this.state);
};
this.forceUpdate();
}
};
render() {
return (
<View style={styles.soundButtonWrapper} key={this.props.name}>
<TouchableOpacity
style={styles.soundButtonPress}
activeOpacity={0.8}
onPress={() => {
toggleSound(this.props.sounds);
}}
>
<Image
style={styles.soundButton}
source={this.state.audioOff ? soundOff : soundOn}
></Image>
<Text style={styles.text}>
Audio {this.state.audioOff ? "off" : "on"}
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
soundButtonWrapper: {
width: "100%",
height: 40,
position: "absolute",
top: 20
},
soundButtonPress: {
width: 40,
height: 40,
position: "absolute",
right: 20
},
soundButton: {
width: 40,
height: 40,
tintColor: "#59BC92"
},
text: {
width: 120,
height: 40,
position: "absolute",
right: 80,
color: "white"
}
});
GlobalSoundButton.propTypes = {
sounds: PropTypes.array
};
我的其他组件的不同之处在于它不起作用,我将其渲染如下:
import GLOBAL from "logic/GlobalState.js";
<GlobalSoundButton
sounds={this.state.allSounds}
audioOff={GLOBAL.homeScreen.state.audioOff}
name="GameScreenKey"
></GlobalSoundButton>
无需将
audioOff
的值保持在该状态。只是根据道具进行渲染。我知道,我一开始就是这么做的,但在那里有相同的问题@arjun。这就是为什么我尝试了这种方法,但没有一种方法奏效:(道具也有同样的问题。在一个屏幕上它能工作,但在另一个屏幕上却不能。你能发布你是如何使用这个组件并向它传递道具的吗?@arjun我用更多应该相关的信息更新了我的问题。谢谢你花时间。所以奇怪的是状态更新了(或者如果我改用道具的话)但在这两种情况下(状态/道具),它只在主屏幕上工作,而不在其他屏幕上工作。不需要在状态中保持audioOff
的值。只需根据道具进行渲染。我知道,这是我最初做的,但在@arjun那里也是同样的问题。这就是为什么我尝试了这种方法,但没有一种方法起作用:(道具也有同样的问题。在一个屏幕上它能工作,但在另一个屏幕上却不能。你能发布你是如何使用这个组件并向它传递道具的吗?@arjun我用更多应该相关的信息更新了我的问题。谢谢你花时间。所以奇怪的是状态更新了(或者如果我改用道具的话)但在这两种情况下(状态/道具),它只在主屏幕上工作,而不在其他屏幕上工作。
import GLOBAL from "logic/GlobalState.js";
<GlobalSoundButton
sounds={this.state.allSounds}
audioOff={GLOBAL.homeScreen.state.audioOff}
name="GameScreenKey"
></GlobalSoundButton>
module.exports = {
homeScreen: null
};