React Native setState不一致[重复]
Posted
技术标签:
【中文标题】React Native setState不一致[重复]【英文标题】:React Native setState is not consistant [duplicate] 【发布时间】:2018-12-23 14:53:20 【问题描述】:这里我的状态在使用 setState.log 后没有更新,大部分时间显示默认值。为什么setState
不一致?
export default class Row extends Component
constructor(props)
super(props);
// icons to listview (arrow icon)
this.icons =
up: require("../../assets/ic_play_circle_down.png"),
down: require("../../assets/ic_play_circle_up.png")
;
this.state =
title: props.title,
// getting screen size (width and height)
let: ( width, height = Dimensions.get("window")),
// collapsed check the listview expanded or not if it is true: list view not expanded
collapsed: true,
isApproved: false,
comment: "dummy comment"
;
acceptApproval = () =>
this.setState( isApproved: true );
console.log("Approved TICK " + this.state.isApproved);
this.verifyApprovals();
;
regectApproval = () =>
this.setState( isApproved: false );
console.log("Approved" + this.state.isApproved);
this.verifyApprovals();
;
【问题讨论】:
因为 setState 是异步的。 那我该如何解决呢? 这里你可以了解setState
:medium.freecodecamp.org/…
【参考方案1】:
你知道setState
是异步的,你应该调用你的第二个函数作为setState的回调
this.setState( isApproved: true , function()
this._setApproval(true)
);
;
_setApproval()
console.log("Approved TICK " + this.state.isApproved);
this.verifyApprovals();
regectApproval = () =>
this.setState( isApproved: false , function()
this._setRejection();
);
;
_setRejection()
console.log("Approved" + this.state.isApproved);
this.verifyApprovals();
【讨论】:
我解决了我的问题。我不知道“setState -> 异步” 好的..你能把工作的代码放在这里@HRCJ acceptApproval = () => this.setState( isApproved: true, collapsed: !this.state.collapsed , function() this.verifyApprovals(); ); ;以上是关于React Native setState不一致[重复]的主要内容,如果未能解决你的问题,请参考以下文章
React setState hook 之前的 param 对象给出了不一致的值
react-native this.setState 导致代码停止运行
react-native如何看待 this.setState()