如何通过 window.href react 传递 props

hen*_* pf 1 javascript reactjs

我之前已经将道具传递到不同的组件和页面,但这已经通过链接或只是将这些添加到组件标签本身。

我在这里遇到的问题是重定向不是通过链接标签或组件标签,而是我只是使用 window.locatio.href ="whatever the url is"。

我只是想将一个变量传递给这个(我在这种情况下在技术上进行了刷新,因此 window.location.reload() 也可以在可能的情况下工作)。

我将如何通过这个变量。使用 express 时,您可以使用类似于(可能不是确切的语法)“./page${variableYouWant}”的端点执行 fetch 语句,然后使用 req.params.variableYouWant 访问 express 文件。

是否可以通过这种方式传递变量,然后我将如何访问它。

这是我的代码中最重要的片段。

pageRelocator(mssg) {
    if (mssg.length < 35) {
      toast.info(`${mssg}`, {

        draggable: true,

        autoClose: 1500
      });
      window.location.href = "http://localhost:3000/completed-assessment";
    } else if (mssg.length > 35) {
      toast.error(`${mssg}`, {

        draggable: true,

        autoClose: 1500
      });
//Here I would like to pass a variable
      window.location.href = "http://localhost:3000/user-questions";
    }
  }

Run Code Online (Sandbox Code Playgroud)

编辑 -

componentDidMount() {
    const search = this.props.location.mssg;
    alert(search); // returns the URL query String
    const params = new URLSearchParams(search);
    const IdFromURL = params.get("mssg");

    this.setState({
      questions: this.getItems(),
      WorkStations: this.getWorkStations()
    });
  }
  pageRelocator(mssg) {
    if (mssg.length < 35) {
      window.location.href = "http://localhost:3000/completed-assessment";
    } else if (mssg.length > 35) {
      window.location.href = `http://localhost:3000/user-questions?mssg=${mssg}`;
    }
  }
Run Code Online (Sandbox Code Playgroud)

Abd*_*bid 7

尝试使用URLSearchParamswhich 定义实用方法来处理 URL.so 的查询字符串,以附加您将执行的变量

var id=5;
window.location.href = `http://localhost:3000/user-questions?id=${id}`;
Run Code Online (Sandbox Code Playgroud)

并从您要执行的 URL 中检索 id

const search = props.location.search; // returns the URL query String
const params = new URLSearchParams(search); 
const IdFromURL = params.get('id'); 
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助