我真的不確定我做錯了什么
請幫忙...
有沒有更好的方法來訪問在 useEffect 中宣告的變數?
謝謝
所以我有以下代碼 - 但我收到錯誤:
[TypeError: "setDevice" is read-only]
const [device, setDevice] = useState( '' );
React.useEffect(() => {
const device_id = async () => {
var DeviceInfo = require('react-native-device-info');
var deviceId = DeviceInfo.getUniqueId();
const filePath = RNFS.DocumentDirectoryPath deviceId "_secret.json";
if (await RNFS.exists(filePath)){
RNFS.readFile(filePath, 'utf8')
.then((contents) => {
try{
// setDev = String(contents);
var JSONObject = JSON.parse(contents);
console.log(JSONObject['device_id']);
setDevice = JSONObject['device_id'];
}catch(err){
console.log("Error: ", err);
}
});
console.log("FILE EXISTS: " filePath);
} else {
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i )
text = possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var dev_id = makeid() deviceId;
var id = '{"device_id" : "' dev_id '"}';
RNFS.writeFile(filePath, id, 'utf8')
.then((success) => {
console.log('FILE WRITTEN!');
navigation.dispatch(resetReachOutPreferences)
})
.catch((err) => {
console.log(err.message);
});
}
}
device_id();
}, []);
console.log("ID: " device);
我試過 useState(null)
uj5u.com熱心網友回復:
從State hook 上的 React 檔案:
useState 回傳什么?它回傳一對值:當前狀態和更新它的函式。
所以在這種情況下,setDevice是一個可以用來更新值的函式device(這將反映在后續的渲染中)。而不是分配給它,你應該用新值作為它的引數來呼叫它,例如:
setDevice(contents);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/455674.html
標籤:javascript 反应式
