【问题标题】:Avoid showing an element while the promise is being fufilled在履行承诺时避免显示元素
【发布时间】:2020-02-29 02:25:49
【问题描述】:

我有一个承诺,它需要一些时间 as mentioned in this question 来实现,因为它会解析来自 API 的值。

我们只想在某些情况下显示/隐藏该功能。在一般情况下,我们希望该功能仅可见。

问题在于,直到实现承诺 - 该字段是可见的。根据网络速度,承诺需要 1-1.5 秒才能实现。 1-1.5 秒后元素被隐藏。这给最终用户带来了奇怪的体验。

这是这种疯狂用户体验的时间线:

  1. 时间 A - 元素可见
  2. 时间 A 和 1-1.5 秒的总和 - 元素被隐藏

我正在尝试了解是否有更好的方法来处理这种情况。

【问题讨论】:

  • 您能否提供一个您用来实现此目的的代码示例?如果您使用状态变量来隐藏/显示元素,则在将其设置为 true 之前它不应该是可见的。
  • 通常,对于您不知道它是否应该在一段时间内可见的元素的用户界面解决方案是最初将元素设为隐藏,并且仅在您响应时才使其可见回来,你现在知道它应该是可见的。这可以使每次向用户展示时都应该隐藏的东西。换句话说,默认条件是它们是隐藏的,并且只有在您知道它们应该可见时才可见。

标签: javascript node.js reactjs user-interface


【解决方案1】:

您可以为此使用条件。以下示例显示了某些元素如何仅在 API 数据到达后显示。

const { useState } = React;
const { render } = ReactDOM;

function App() {
  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState(false);
  
  const setLoadingState = () => {
    setData();
    setIsLoading(true);
  }
  
  const getApiData = () => {
    setLoadingState();
    setTimeout(() => { // <-- Add some additional 'delay' for the sake of this demo
      fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(res => res.json())
        .then(json => setData(JSON.stringify(json, null, 2)))
        .catch(err => setData(JSON.stringify(err, null, 2)))
        .finally(() => setIsLoading(false));    
    }, 1300);
  }
  
  return (
    <div>
      <button disabled={isLoading} onClick={getApiData}>Load API Data</button>
      {data && // <-- Conditional statement, like saying `if (data) { ... }`
        <div>
          <h4 style={{color: 'blue'}}>I am some fancy html that is hidden before my API data arrives</h4>
          <pre>{data}</pre>
        </div>}
      {isLoading && // <-- Another conditional..
        <h3>Loading...</h3>}
    </div>
  );
}

render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2016-06-05
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多