【问题标题】:React Native doesn't update child component propsReact Native 不更新子组件道具
【发布时间】:2017-05-10 12:39:15
【问题描述】:

我正在做一个 React Native 项目,我意识到 React Native 似乎破坏了 React 流程(父母到孩子)道具更新。

基本上,我从“App”组件调用“Menu”组件,将一个道具传递给“Menu”。但是,当我更新“应用程序”状态时,“菜单”上的道具应该更新,但这不会发生。我做错了吗?

这是我的代码:

App.js

import React from 'react';
import {
 View,
 Text
} from 'react-native';

import Menu from './Menu';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      opacity: 2
    }
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        opacity: 4
      });
    }, 3000);
  }

  render() {
    return(
      <View>
        <Menu propOpacity={this.state.opacity} />
      </View>
    );
  }
}

export default App;

Menu.js

import React from 'react';
import {
View,
Text
} from 'react-native';

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpacity: props.propOpacity
    }
  }

  render() {
    return(
      <View>
        <Text>Menu opacity: {this.state.menuOpacity}</Text>
      </View>
    );
  }
}

Menu.propTypes = {
  propOpacity: React.PropTypes.number
}

Menu.defaultProps = {
  propOpacity: 1
}

export default Menu;

【问题讨论】:

  • 你不能在 didmount 中设置状态,所以请在其他地方更新。
  • @Codesingh 是的,您可以通过cDM 方法设置状态。您不能通过 render 方法这样做。

标签: reactjs react-native


【解决方案1】:

React 没有破坏数据流……你是。在初始状态初始化后,当父级发送更新的道具时,您会忘记更新菜单的状态。

试试这个...

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpacity: props.propOpacity
    }
  }

  componentWillUpdate(nextProps, nextState) {
      nextState.menuOpacity = nextProps.propOpacity;
  }

  render() {
    return(
      <View>
        <Text>Menu opacity: {this.state.menuOpacity}</Text>
      </View>
    );
  }
}

【讨论】:

  • 你不能像这样在 willupdate 里面更新状态
  • 拜托,你为什么这么认为?这是合法的方式,不会破坏任何东西并为您节省另一个重新渲染。仔细看看构造函数 - 状态是从父传递的 prop 初始化的。我在componentWillUpdate 方法中使用了相同的模式。组件即将更新(您无法阻止这种情况发生)并且状态将替换为修改后的nextState
  • 嘿@Andreyco,您的解决方案有效。首先,感谢您的帮助。所以,我有一个问题,为什么我在这里需要 componentWillUpdate 而不是在纯 React 应用程序中?我用纯 React 做了一个例子,没有 componentWillUpdate 一切正常。
  • 您需要它,因为您从传递的props 发起了state(原因我不知道)。您可以在示例中完全跳过 state 并使用无状态函数组件(这就是您所说的“纯反应应用程序”)。但是,如果您将来需要从 prop 计算状态,这是一种可能性 :)
  • 好的,明白了。我正在使用状态,因为我的真实应用程序使用来自 React Native 的“Animated.View”,这需要状态。因此,我查看了 React 的文档,发现“componentWillReceiveProps”也可以。有什么理由我应该使用“componentWillUpdate”而不是“componentWillReceiveProps”吗?
猜你喜欢
  • 2018-06-03
  • 2019-04-29
  • 2019-08-03
  • 1970-01-01
  • 2019-05-25
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多