钩子第一次没有设置状态

IT技术 javascript reactjs react-native
2021-04-28 09:46:33

我是 React Native 的初学者,在我的项目中,我在按下按钮用户名和身份验证状态后搜索了文件,但没有初始化我的变量,但在第二次按下后,我的状态初始化并显示数据可以帮助我解决这个问题。谢谢

const DataFeatch = async () => {

await Authentication_Creator();

let SearchData = {
  "user_name": await UserName,
  "user_authentication": await User_Authentication,
};    
try {
  let response = await fetch('fechURL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(SearchData),
  });
  let json = await response.json();
  if (json == 'no result') {
    something
  } else {
    SetDataSource(json);
  }
}
catch{
 ERRoR
}

}

我的 Authentication_Creator 是

  const Authentication_Creator = async () => {

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + 'path';
var data = await RNFS.readFile(path, 'utf8');
var mydata = await JSON.parse(data);
let hash = data;
hash = md5(hash);

SetUserName(() => mydata.UserName);
SetUser_Authentication(() => hash);

}

1个回答

您必须对代码进行一些更改,不能使用 await Username,它对react状态没有影响。

您可以像这样更改 Authentication_Creator :

 const Authentication_Creator = async () => {

    var RNFS = require('react-native-fs');
    var path = RNFS.DocumentDirectoryPath + 'path';
    var data = await RNFS.readFile(path, 'utf8');
    var mydata = await JSON.parse(data);
    let hash = data;
    hash = md5(hash);

    return { user_name: myData.UserName, user_authentication: hash};

}

之后在您的数据提取功能中:

const DataFeatch = async () => {

let SearchData = await Authentication_Creator();

// and other code

}