Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

React state更新的问题

页面中有一组Switch组件,默认全部开启,通过改变switchValue控制开关
image.png

开关数据从一个常量文件中导入的

export const stationStatusSwitch = [
    {
      switchValue: true, 
      id: 1
    },
    {
      switchValue: true, 
      id: 2
    },
    {
      switchValue: true, 
      id: 3
    },
    {
      switchValue: true, 
      id: 4
    },
    {
      switchValue: true, 
      id: 5
    },
    {
      switchValue: true, 
      id: 6
    },
    {
      switchValue: true, 
      id: 7
    }
  ]
  import { stationStatusSwitch } from "./constants";`
  constructor(props) {
    this.state = {
        stationStatusSwitch,
    }
  }

现在有个问题就是:如果把开关关闭也就是switchValue设为false然后再回到上个页面再重新进入这个页面,这个时候开关还是关闭的,switchValue的值还是false,在class外边打印stationStatusSwitch发现switchValue也是false。
这个就不明白了,回到上个页面再进入这个页面,state不应该被重置吗,我改变的是state为什么还是影响到导入的数组。如果我把stationStatusSwitch放到当前页面的state中就不会有这个问题,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

按照题主描述,应该是navigation 切换screen 时 navigation使用的前面已经创建的路由栈中的页面,stack 中保留了上次页面的状态。
因题主描述信息不足,可以尝试下一下方法:

  1. 使用 navigation.push 跳转至此页面;
  2. 不要直接使用元数据(常量),请深拷贝一份
this.state = {
        stationStatusSwitch: depthCopy(stationStatusSwitch)// depthCopy 深拷贝需要题主自己实现下,
    }

原则上 使用navigation.push 应该能解决你的问题了,但是注意下返回不能再使用 goBack()

如果不能解决你的问题,请再提供以下信息:

  1. 出现问题平台,ios or Android
  2. 导航方式 navigation.navigate / push /replace
  3. 路由配置

另外 一楼在胡扯


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...