【发布时间】:2020-01-16 21:40:05
【问题描述】:
免责声明:这是我的第一个 react 应用程序,我是一名仍在学习的 cs 学生
我做了一些控制台日志,props 和 nextprops 是正确的,但除非与之交互,否则它不会正确呈现。
我必须在不透明度更改之前单击一个按钮两次,并且其他按钮的不透明度不会更新为 1。
我已经通过很多谷歌搜索并尝试了一些东西,但它们都没有奏效。
具有 2 个来自 WeekMenu.js 的按钮实例的类
class WeekMenu extends Component{
render(){
return(
<View style={styles.container}>
<TouchableOpacity
style={this.props.daysOfWeek[0] ? {opacity: 0.5} : {opacity: 1}}
onPress={() =>this.props.dayClicked(0)}
>
<View style={styles.left}>
<Text style={styles.text}>S</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
style={this.props.daysOfWeek[1] ? {opacity: 0.5} : {opacity: 1}}
onPress={() =>this.props.dayClicked(1)}
>
<View style={styles.middle}>
<Text style={styles.text}>M</Text>
</View>
</TouchableOpacity>
WeekMenu.js 续
function mapStateToProps(state){
return{
daysOfWeek: state.daysOfWeek
}
}
function mapDispatchToProps(dispatch){
return{
dayClicked: (value) => dispatch({type: 'DAY_CLICKED', value})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(WeekMenu)
App.js
const initialState = {
daysOfWeek: [0, 0, 0, 0, 0, 0, 1]
}
changeActiveDay = (day) => {
newDaysOfWeek = new Array(7).fill(0)
newDaysOfWeek[day] = 1
return newDaysOfWeek
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'DAY_CLICKED':
return {
...state,
daysOfWeek: changeActiveDay(action.value)
}
default:
return state
}
}
const store = createStore(reducer)
更新 #1:
class WeekMenu extends Component{
state = {
daysOfWeek: this.props.daysOfWeek
}
componentDidUpdate(prevProps){
if(prevProps.daysOfWeek !== this.props.daysOfWeek)
this.setState({daysOfWeek: this.props.daysOfWeek})
}
render(){
return(
<View style={styles.container}>
<TouchableOpacity
style={this.state.daysOfWeek[0] ? {opacity: 0.5} : {opacity: 1}}
onPress={() => this.props.dayClicked(0)}
>
<View style={styles.left}>
<Text style={styles.text}>S</Text>
</View>
</TouchableOpacity>
...
【问题讨论】:
-
检查组件将收到的道具
-
你能为此创建一个codepen吗?
标签: javascript react-native react-redux render