基于异步函数返回布尔值的jsx中的渲染组件

时间:2020-04-23 13:22:25

标签: reactjs

我试图基于异步/等待函数的返回值来渲染html元素。我似乎无法正常工作。

下面是被调用的异步函数

const isAuthorized= async() => {
  const isAuthorized = await Promise.resolve().then(() => false);
  console.log("isAuthorized =", isAuthorized);
  return isAuthorized;
}

下面是jsx:

const ComponentName= () => {
    return (
        <div>
            {Promise.resolve(isAuthorized()).then(res => {res ? <p>User is authorized</p> : <p>User is not authorized</p>})}
        </div>
    )
}

export default ComponentName;

这是我得到的错误:

enter image description here

3 个答案:

答案 0 :(得分:1)

您需要在组件中保留一个状态以跟踪您的用户是否被授权。然后,您可以使用useEffect挂钩检查状态。您的组件应根据状态更改进行渲染(然后重新渲染)。

https://codesandbox.io/s/promiseinuseeffect-do22b?file=/src/App.js

答案 1 :(得分:0)

在React中是不可能的。

1)尝试使用async / await

2)让您在useEffect(componendDidUpdate)中准备数据

const ComponentName = () => {
    const [isAuth, setIsAuth] = setState(undefined);
    React.useEffect(() => {
        (async function() {
            if (!isAuth) {
                const result = await isAuthorized();
                setIsAuth(result);
            }
        })();
    }, []);
    const text = isAuth ? 'User is authorized' : 'User is not authorized';
    return (
        <div>
            <p>{text}</p>
        </div>
    );
};

答案 2 :(得分:0)

我能够使用状态使它工作

class ComponentName extends Component {
    constructor(props) {
        super(props);
        this.state= {
            isAuthorized: false
        }
    }

    async componentDidMount(){
        const isAuthorized = await Promise.resolve().then(() => false);
        this.setState({isAuthorized: isAuthorized});
    }

    render() {
        return (
            <div>
                {this.state.isAuthorized ? <p>User is authorized</p> : <p>User is not authorized</p>}
            </div>
        )
    }
}

但是,我认为将这样的变量作为dom的状态并不安全吗?

相关问题