使用 setTimeout() 在 React 中使用一些超时渲染列表

Rendering a list in React with some timeout usig setTimeout()

我是 React 新手,我试图使用 json 数组显示帖子列表,并希望列表在特定秒数的超时后呈现,但列表未使用超时呈现功能。

render(){
        const posts=[
            { title:"Post One", body:"This is post one"},
            { title:"Post Two", body:"This is post two"}
        ]
        return(
            <>
            <div className={"container"}>
                <h2>{this.state.message}</h2>
                <button className="primary" onClick={this.handleChange}>Change</button>
                <ul>
                <Getpost postDet={posts} />
                </ul>
            </div>
            </>
        )
    }
export function Getpost(posts){
   // this.setTimeout(()=>{
        //return(

            //console.log("waiting for list to populate")
            return(
                <div>
                setTimeout(()=>{
                    posts.postDet.map((post)=>{
                        return <li key={post.title}>{post.title}</li>;
                    })
                },2000)
                </div>
            )       
            }

任何人都可以帮助我哪里错了或者我怎样才能完成我的任务

问题#1

目前,您正在尝试获取要执行的 JavaScript 代码,但将其放在 JSX <div> 元素中,这无法正常工作(它只会按原样呈现代码) .

这个

function GetPosts() {
  return (
    <div>
    console.log('hey')
    </div>
  )
}

根本不会打印任何东西,它只会向用户显示console.log('hey')。但是,您可以通过将代码放在大括号内来执行代码,如下所示:

function GetPosts() {
  return (
    <div>
    {"hello" + " world"}
    </div>
  )
}

如果要包含动态数据,可以从大括号内调用函数。

问题#2

setTimeout 函数 returns 一个标识正在进行的超时的数字(并允许您在它执行其函数之前清除它),但它 returns 这个数字立即。延迟后显示数据比这更复杂。

例如,您可以使用反应钩子,这已经是一个非常高级的主题。它的外观如下:

function GetPosts(props) {
  // Create a local state for your posts (and initialize it with an empty array)
  const [posts, setPosts] = useState([]);

  // Execute setTimeout *only* when the component is created (once)
  useEffect(() => {
    const timeoutID = setTimeout(() => setPosts(props.postDet), 2000);

    // You can optionally (but it's extremely recommended) return another function that will be invoked when the component is unmounted/deleted
    return (() => clearTimout(timeoutID));
  }, []);

  return (
    <div>
      {posts.map((post)=>{
         return <li key={post.title}>{post.title}</li>;
      })}
    </div>
  )
}

这已经很复杂了,而且你似乎是 JS 的初学者,所以我强烈建议你在深入研究像 React 这样复杂的框架之前先阅读或多学一点。希望我能帮上忙,让自己说清楚。

如果您对 React 中的钩子有更多了解,这会更好。但我假设你没有。所以我在下面给你一个更简单的更正。

更改下面的代码,

export function Getpost(posts){
   // this.setTimeout(()=>{
        //return(

            //console.log("waiting for list to populate")
            return(
                <div>
                setTimeout(()=>{
                    posts.postDet.map((post)=>{
                        return <li key={post.title}>{post.title}</li>;
                    })
                },2000)
                </div>
            )       
            }

像这样的事情

class Getpost extends React.Component {
   constructor(props){
      super(props)
      this.setState = {
         hasFinishedLoading : false
      }

      this.setHasFinisedLoading = this.setHasFinisedLoading.bind(this)
   }

  setHasFinisedLoading(event){
     setTimeout(()=>{
        // tell the component that you have finished loading. It will reload the UI automatically
        this.setState({hasFinishedLoading : true});

     },2000)
  }

   render (){
      return(
                <div>
                  {this.state.hasFinishedLoading ? posts.postDet.map((post)=>{
                        return <li key={post.title}>{post.title}</li>;
                    }) : <p></p>
                  }
                </div>
            )  
   }                

我认为这个自定义挂钩对您更有帮助https://github.com/streamich/react-use/blob/master/docs/useTimeout.md

你只需要安装 react-use

import useTimeout from 'react-use/lib/useTimeout';

const PostList = (props) =>{
    const ms = props.ms || 5000;
    const [isReady, cancel] = useTimeout(ms);

    const posts=[
        { title:"Post One", body:"This is post one"},
        { title:"Post Two", body:"This is post two"}
    ]
    return(
        <>
        <div className={"container"}>
            <h2>{this.state.message}</h2>
            <button 
              className="primary" 
              onClick={this.handleChange}                    
             >
                Change
            </button>
            <ul>
              {isReady && <Getpost postDet={posts} />}
            </ul>
        </div>
        </>
    )
}

在 React 中,如果您想更改任何内容并希望它出现在屏幕上,唯一的方法就是渲染。

渲染的唯一方法是更改​​状态。

所以简单的答案是您需要维护一个具有空值的状态。在 componentdidmount 上,您可以拥有更改状态的超时逻辑。

你可以这样使用

constructor(props){
        super(props)
        this.state = {
            posts: []
        }
    }
    componentDidMount(){
        const posts = [
            { title: "Post One", body: "This is post one" },
            { title: "Post Two", body: "This is post two" }
        ]

        setTimeout(() => {
            this.setState({ posts: posts })
        }, 2000)
    }

    render(){

        return (
            <>
                <div className={"container"}>
                    <h2>{this.state.message}</h2>
                    <button className="primary" onClick={this.handleChange}>Change</button>
                    <ul>
                        <Getpost postDet={this.state.posts} />
                    </ul>
                </div>
            </>
        )
    }




    export function Getpost(posts) {

        return (
            <div>
                posts.postDet&& posts.postDet.length && posts.postDet.map((post)=>{
                            return <li key={post.title}>{post.title}</li>;
            })
                    </div>
        )
    }