【问题标题】:How to update UI data fetched by getServerSideProps in Nextjs如何在 Nextjs 中更新 getServerSideProps 获取的 UI 数据
【发布时间】:2020-09-05 13:52:50
【问题描述】:
function Page({ data }) {
  // Render data...
  const itemList = data.items.map(item => {
    return <Item key = {item.id} />
  })
  return(
    <div>
      {itemList}
    </div>
  )
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page

我想在 data.items 数组中推送一个新项目并更新 UI。

通常这可以通过useState() 实现,但在这种情况下,数据是在服务器端获取的。

有没有简单的方法来实现这一点?

【问题讨论】:

    标签: next.js


    【解决方案1】:
    • 为什么不将新项目推送到 getServerSideProps 中并将最终数据作为道具发送?我做了这样的事情:-
    import Axios from "axios";
    
    const index = ({ data }) => {
    
      return (
        <div>
          <ul>
            {data.map(post => <li key={post.id}>
              {post.title}
            </li>)}
          </ul>
        </div>
      )
    }
    
    export const getServerSideProps = async () => {
      const res = await Axios(`https://jsonplaceholder.typicode.com/posts`);
      const newPost = {
        userId: 10,
        id: 101,
        title: 'at nam consequatur ea labore ea harum',
        body: 'cupiditate quo est a modi nesciunt soluta\n' +
          'ipsa voluptas error itaque dicta in\n' +
          'autem qui minus magnam et distinctio eum\n' +
          'accusamus ratione error aut'
      }
      const data = [...res.data, newPost];
      return {
        props: {
          data
        }
      }
    }
    
    export default index;
    
    

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2021-12-31
      • 2021-04-22
      • 2020-07-25
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2021-12-30
      • 2021-07-04
      相关资源
      最近更新 更多