gpt4 book ai didi

javascript - React - 变量未定义而不是 true/false - 组件首先呈现?

转载 作者:行者123 更新时间:2023-11-30 15:23:41 25 4
gpt4 key购买 nike

好吧,我想要实现的是一个函数,它根据文件是否存在返回具有不同标签的按钮。到目前为止一切顺利,代码本身似乎可以正常工作,但顺序错误。我所做的是在执行实际检查的函数部分打印出“文件确实存在”或“不存在”,将 boolean 保存到 test 变量,使用所述变量来确定最终返回哪个按钮。

现在发生了什么,即使第一部分打印出“文件确实存在”(应该将 true 保存到 test),console.log (test) 再往下一点返回 undefined ,这当然会导致条件不起作用。

我确定我忽略了一些非常简单的事情,但我就是想不通。

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import fs from 'fs';

var ConfigChecker = React.createClass({

render: function(){

var test;
fs.open('./App.js', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.log('file does not exist');
test = false;
}

throw err;
}
console.log('this should be executed first:');
console.log('file does exist')
test = true;
});


if (test)
{
console.log("this should be executed last:");
console.log(test);
return (<RaisedButton label="true" />);
}
else {
console.log("this should be executed last:");
console.log(test);
return (<RaisedButton label="false" />);
}
}


});

export default ConfigChecker;

this is what gets returned in the dev console

最佳答案

异步调用并不像您想象的那样工作。任何时候你在 JavaScript 中看到一个异步函数(期望一个回调,返回一个 Promise)时,在你的脑海中为函数的名称加上前缀“registerInterestIn{functionName}”。所以 fs.open 变成了 fs.registerInterestInOpen

考虑到这一点,您的代码现在看起来像这样:

var test;
fs.registerInterestInOpen('./App.js', 'r', ...);
// Still undefined here, we just registered an interest
// in the results of opening ./App.js ... nothing has
// actually *happened* yet.
if (test) {

} else {

}

// And when we get down here, JavaScript will actually *do*
// the opening, and call our callback with the result, when
// the operating system gets back to us with the data or an error

这个问题怎么处理?

您需要使用一些 React 状态,以便了解您的组件处于三种状态中的哪一种(等待确定文件是否存在、文件存在、文件不存在)。然后您需要将回调中的状态更改为 fs.open 以告诉 React 重新渲染您的组件:

const ConfigChecker = React.createClass({
getInitialState() {
return { test: null };
},
componentDidMount() {
fs.open('./App.js', 'r', (err, fd) => {
if (err && err.code === 'ENOENT') {
console.log('file does not exist');
return this.setState(() => { test: false});
}
this.setState(() => { test: true});
});
},
render() {
if (this.state.test == null) {
return 'Loading ...';
} else {
return <RaisedButton label={this.state.test} />;
}
}

关于javascript - React - 变量未定义而不是 true/false - 组件首先呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43307812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com