【发布时间】: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 ? <Table...? -
也尝试添加一些
console.log()s 以查看您“丢失”数据的位置
标签: reactjs react-props