【问题标题】:react's state value not passing to props反应状态值不传递给道具
【发布时间】:2019-11-16 02:16:05
【问题描述】:

我正在渲染从 Redux 商店获得的用户列表(我将它存储在变量 data 中)。将用户加载到 Redux 是异步的,这就是为什么它需要一些时间并且我的 List 必须重新渲染。我过滤这些数据并将其保存在 List 的状态中,并尝试将其作为道具发送到 Table它永远不会将状态的值传递给我的表的道具 em>。

const getData = data => {...}

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      displayData: [],
    };
  }

  static getDerivedStateFromProps(props) {
    return props.data ? { displayData: getData(props.data) } : null;
  }

  shouldComponentUpdate(nextProps) {
    const { data } = this.props;
    return data === undefined && data !== nextProps.data;
  }

  render() {
    const { displayData } = this.state;
    return data ? <Table displayData={displayData} /> : <h1>Loading...</h1>;
  }
}
const mapStateToProps = ({ data }) => ({
  data: data.users,
});
export default connect(mapStateToProps)(List);

上层组件:

class App extends React.Component {
  componentDidMount() {
    const { loadData, loadFromStorage } = this.props;
    loadData();
  }
  render() {
      return (
        <Router history={history}>
          <Header history={history} />
          <Switch>
            <Route path="/list" render={props => <List {...props} />} />
            ...
          </Switch>
        </Router>
      );
    }
  }
}
const mapDispatchToProps = { loadData: LOAD_DATA };

export default connect(null, mapDispatchToProps)(App);

它只是设置我的 List 组件的状态,并且永远不会在 Table 更改时将任何其他道具传递给它们(我使用 React 扩展并检查了道具和状态) 我该如何解决这个问题?
P.S.:我希望这个组件在我每次获得新道具时都重新渲染

【问题讨论】:

  • 你的react-reduxconnect在哪里?你还需要一个mapStateToProps 函数。另外,您需要在 componentDidMount 方法上“加载”您的数据(因为您有 Redux 实现)
  • @Zoti 已连接。我只是认为没有必要包括在这里。它在componentDidMount的上层组件中加载数据
  • 你能注释掉你的constructor方法并在你的reducer中初始化你的状态吗?
  • 数据在你的渲染上下文和你的类之外都丢失了。可能是return displayData ? &lt;Table...
  • 也尝试添加一些console.log()s 以查看您“丢失”数据的位置

标签: reactjs react-props


【解决方案1】:

尝试删除“data === undefined”,同时返回this.state.data !== nextState.data,按以下方式操作:

shouldComponentUpdate(nextProps, nextState) {
    return this.state.data !== nextState.data;
}

我不知道你如何为你的 reducer 文件中的 data 属性设置你的 reducer 的默认状态。如果 reducer 文件中数据的初始状态是 {}[]null,您的代码将阻止组件更新。

同样在你的情况下,你的表只从状态中获取数据,而不是道具。 state 重置后,this.props 和 nextProps 可能已经相等了,所以最好使用 this.state。

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 2021-09-27
    • 1970-01-01
    • 2018-09-02
    • 2018-12-25
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多