反应本机useState未设置状态

时间:2020-10-14 03:06:09

标签: javascript react-native state use-state

我的代码如下:

const [clientID, setClientID] = useState({});

// explodeClientID is an object
let explodeClientID = ClientIDFormatter(routeParams.QRData);
// I assign that variable to me clientID state:
setClientID(explodeClientID);

// I logged the variable:
console.log("Exploded Client ID:")
console.log(explodeClientID);
/* OUTPUT: 
Exploded Client ID:
Object {
  "BR_ID": 1,        
  "ClientChkID": 4,  
  "ClientID": 599920,
} */

// I logged the state:
console.log("Client ID: ");
console.log(clientID);
/* OUTPUT 
Client ID:
Object {}
*/

如您所见,主要问题是当我将explodeClientID分配给常规变量时,它具有值。但是当我使用setState进行更新时,它仍然返回一个空对象。这根本不是问题,因为它不是我需要等待的API调用。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法吗?

const [clientID, setClientID] = useState({});

// explodeClientID is an object
let explodeClientID = ClientIDFormatter(routeParams.QRData);
// I assign that variable to me clientID state:
setClientID(explodeClientID);

// I logged the variable:
console.log("Exploded Client ID:")
console.log(explodeClientID);
/* OUTPUT: 
Exploded Client ID:
Object {
  "BR_ID": 1,        
  "ClientChkID": 4,  
  "ClientID": 599920,
} */

React.useEfect(()=>{
console.log(clientID)
}, [clientID])