返回条件渲染在React中不显示Fetch元素。

huangapple go评论63阅读模式
英文:

Return conditional rendering in React doesn't show Fetch elemets

问题

嗨,谢谢你的时间。我对React还很新,所以正在尝试学习如何使用它。我正在从API中检索项目,当我成功获取后,我会使用setState来根据响应创建新组件 - 对此我没有任何问题。但是,我尝试渲染两个不同的组件,一个用于加载状态,当我们等待服务器响应时,另一个用于实际元素。我知道可以使用三元条件来做到这一点,但我认为匿名函数看起来更好。这对于"加载中..."状态效果很好,但在我从服务器获取响应后,它不显示任何内容。即使我在那里抛出静态数据 - 它也不显示。这个问题是如何解决的?因为如果我调试地图中的每个元素 - 我会得到响应 - 但它就是不想渲染它们。

英文:

Hey guys thanks for your time. I'm still new to React so I'm trying to learn how to use it. I'm retrieving items from an API and after I'm getting a success, I push the setState to create the new components from the response - and I don't have any problems with that.
But I was trying to render two different components, one for the loading state when we are waiting for a response from the server, and the actual elements. And I know there is a way to do it with a ternary condition. But I think an anonymous function looks better. And this works well with the "Loading..." state, but after I get the response from the server, it doesn't display anything. If I'll throw even static data there - it doesn't show. How this thing works like? Cause If I'll debug each element in map - I'll have my response - but It just don't want to render them.

export function Main(){

  const [state, setState] = useState({users: []});
  const temporaryUsers = state.users;
  useEffect(() => {
      fetch(`https://randomuser.me/api/?results=20`)
      .then(res => res.json())
      .then(json => {
        temporaryUsers.push(json);
        setState({
          users: temporaryUsers
        });
      });
        
    },[])
  
      return(
        <>
          {(() => {
            if (state.users[0] != undefined){
              state.users[0].results.map((elem) => {
                return(
                  <User  props={elem} />
                )
              })
              
            } else{
              return (
                <p style={{textAlign:"center", display:"block", width:"100%"}}>Loading...</p>
              ) 
            }
          })()}
        </>
        
      )
  
}

答案1

得分: 2

已经在React Playground中实现了这个功能,使用了静态数据并加入了延迟。而不是直接修改temporaryUsers数组并推送响应,你应该创建一个新的数组来存储响应数据,然后使用这个新数组来更新状态。

export function Main() {
  const [state, setState] = useState({ users: [] });

  useEffect(() => {
    fetch("https://randomuser.me/api/?results=20")
      .then((res) => res.json())
      .then((json) => {
        setState({ users: json.results });
      });
  }, []);

  return (
    <>
      {state.users.length > 0 ? (
        state.users.map((elem) => <User key={elem.id} props={elem} />)
      ) : (
        <p style={{ textAlign: "center", display: "block", width: "100%" }}>
          Loading...
        </p>
      )}
    </>
  );
}

你可以在React Playground的这里查看实现的示例。

英文:

Update:
Implemented it in react playground here using static data with delay.

<hr>

Instead of directly modifying the temporaryUsers array and pushing the response, you should create a new array with the response data and then update the state using that new array.

export function Main() {
  const [state, setState] = useState({ users: [] });

  useEffect(() =&gt; {
    fetch(&quot;https://randomuser.me/api/?results=20&quot;)
      .then((res) =&gt; res.json())
      .then((json) =&gt; {
        setState({ users: json.results });
      });
  }, []);

  return (
    &lt;&gt;
      {state.users.length &gt; 0 ? (
        state.users.map((elem) =&gt; &lt;User key={elem.id} props={elem} /&gt;)
      ) : (
        &lt;p style={{ textAlign: &quot;center&quot;, display: &quot;block&quot;, width: &quot;100%&quot; }}&gt;
          Loading...
        &lt;/p&gt;
      )}
    &lt;/&gt;
  );
}

答案2

得分: 0

地图循环应该是:

state.users[0].results.map((elem) => (
  <User props={elem} />
))
英文:

The map loop should be:

state.users[0].results.map((elem) =&gt;(
              &lt;User  props={elem} /&gt;
            ))

答案3

得分: 0

返回翻译好的部分:

The return block should be

<>
  {state.users[0]?.length === 0
    ? <p>...加载中</p> 
    : state.users[0]?.results.map((item, key) => <User {...item} key={key}/>)
  }
</>

And your User component

export const User = (props) => {
  return (
    <div>{props.gender}</div>
  )
}
英文:

The return block should be

  &lt;&gt;
{ state.users[0]?.length===0
    ? &lt;p&gt;...loading&lt;/p&gt; 
    : state.users[0]?.results.map((item,key)=&gt;&lt;User{...item} key={key}/&gt;)
}
&lt;/&gt;   

And your User component

    export const User = (props) =&gt; {
      return (
        &lt;div&gt;{props.gender}&lt;/div&gt;
      )

}

huangapple
  • 本文由 发表于 2023年5月30日 07:35:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定