无法在 React 的变量中设置值
Not able to set the value in a variable in 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 中 deprecated/consider 不安全。 https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops。这可能是您的错误的原因。
b) getDerivedStateFromProps
是用于此目的的首选生命周期方法 https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
c) 或者,您可以将此组件重构为功能组件并使用 React hooks
setState 是 async/sync 取决于您调用它的方式。
值已设置,但您还看不到它。尝试在渲染中记录数据。
或者试试这个
this.setState({ data }, () => console.log(this.state.data))
;
使用此 componentWillReceiveProps 方法通常会导致错误和不一致。
更多信息 https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops
在我的 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 中 deprecated/consider 不安全。 https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops。这可能是您的错误的原因。
b) getDerivedStateFromProps
是用于此目的的首选生命周期方法 https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
c) 或者,您可以将此组件重构为功能组件并使用 React hooks
setState 是 async/sync 取决于您调用它的方式。
值已设置,但您还看不到它。尝试在渲染中记录数据。
或者试试这个
this.setState({ data }, () => console.log(this.state.data))
;
使用此 componentWillReceiveProps 方法通常会导致错误和不一致。 更多信息 https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops