钩子第一次没有设置状态

时间:2020-04-20 14:20:26

标签: javascript reactjs react-native

我是本机的新手,在我的项目中,我已经在按下按钮用户名和Authentication状态后搜索了文件,但未初始化我的变量,但是第二次按下后,我的状态初始化并显示数据可以帮助我解决此问题。谢谢

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 个答案:

答案 0 :(得分:1)

您必须在代码中进行一些更改,不能使用await用户名,它对状态没有任何作用。

您可以这样更改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

}