react+next.js遇到的问题及解决

1.使用react-image插件做图片预览,报错:window is not defined。

因为next.js使用的是服务端渲染,没有window。

解决方法是引入的时候,加一个对象 {SSR:false}。

import dynamic from 'next/dynamic'
let Zmage = dynamic(import('react-zmage'), { ssr: false })

 

2.使用this.props.router.query获取不到查询参数。

本地能获取地址栏的参数,但是线上就获取不到。

因为本地开了服务,线上是静态资源,没开服务,所以获取不到。

可以改为window.location来获取并做处理。

封装成一个工具类,随时可以引入使用。

export const getPageQuery = () => {
  const queryStr = window.location.href.split('?')[1];
    const queryArr = queryStr.split('&');
    const queryObj = {};
    queryArr.forEach(d => {
      const arr = d.split('=');
      if (arr[0]) {
        queryObj[arr[0]] = arr[1];
      }
    });
  return queryObj
}

3.使用window.location拿地址栏的数据,数字和字母可以直接解析。

中文需要转码,否则拿到的是一串编码后的数据。

如下图,分别是地址栏的数据,以及从地址栏拿到的数据。

编码方式 let str=encodeURI (数据)

解码 let a=decodeURI (数据)

 

(3参考:https://blog.csdn.net/weixin_41863239/article/details/82083734?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control)

 

 

原文地址:https://www.cnblogs.com/afafaa/p/14217661.html