reactjs - 无法在 React 中的变量中设置值
问题描述
在我的 reactjs 应用程序中,我试图将值设置为变量数据,但它没有被分配。它应该从包含值的 nextProps.samples 分配,我可以登录我的浏览器控制台,这些值。
这是一段代码:
export default class GeofencingSamplesDL extends React.Component {
// eslint-disable-line react/prefer-stateless-function
state = {
data: []
};
componentWillReceiveProps = nextProps => {
let data = [];
if (this.props.samples !== nextProps.samples) {
nextProps.samples.forEach(sample => {
data.push({
Date: sample.timestamp,
Semelle: sample.macAddress,
Gateway: sample.deviceID,
Pas: sample.steps,
RSSI: sample.rssi,
RawSteps: sample.rawSteps
});
// Here values are visible as I print in console
console.log("Sample " + JSON.stringify(sample));
});
// Here values are not getting set
this.setState({ data });
}
};
有什么出路吗?提前致谢。
解决方案
a)componentWillReceiveProps
在最新版本的 React 中被弃用/认为不安全。https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops。这可能是您的错误的原因。
b)getDerivedStateFromProps
是为此目的首选的生命周期方法https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
c) 或者,您可以将此组件重构为功能组件并使用 React 钩子
推荐阅读
- python - 在熊猫中提取特定值后的文本
- php - 如何在 Heroku multi buildpack php + nodejs 中启动 express 服务器
- c++ - C++ 程序在第一次尝试时会给出垃圾,但如果它捕获异常并重试,则会给出正确的值
- wpf - 如何获取用户控件中元素的位置
- javascript - 有没有办法在使用 php 的浏览器中使用 ajax 或类似方法来抓取呈现某些数据的页面
- android - Python/Kivy 应用程序到 Windows 上的 apk - 安装虚拟机后该怎么办?
- android - 打盹模式与网络状态
- angular - 如何获得增量后数字的总值
- json - 在 React-Native 中访问 Json 对象数组
- angular - ionic3 通过 `radio` 更改页面数据