【问题标题】:how to connect two reactjs pages and display same data如何连接两个reactjs页面并显示相同的数据
【发布时间】:2021-02-23 04:19:43
【问题描述】:

这是我的反应代码,我将数据发送到我的服务器并在此页面上获取结果..!实际上我有两个具有相同代码的页面,我只想连接这两个页面。我希望当有人在一个页面上单击(投票)时,结果也将显示在第二页上.. 那么如何连接 2 个页面..?请帮忙

import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import "../../styles.scss";
import { isAutheticated } from "../../auth/helper/index";
import { getPolls, postPoll } from "../helper/coreapicalls";
import axios from "axios";
import { API } from "../../backend";
import { useHistory } from "react-router-dom";

const FullPoll = () => {
  const userId = isAutheticated() && isAutheticated().user._id;
  const [polls, setPoll] = useState([]);
  const [error, seterror] = useState(false);
  const history = useHistory();
  useEffect(() => {
    loadPoll();
  }, [polls]);

  const loadPoll = () => {
    getPolls().then((data) => {
      if (data.error) {
        seterror(data.error);
      } else {
        setPoll(data.reverse());
        console.log(data);
      }
    });
  };

  // Handling user vote
  // Increments the votes count of answer when the user votes
  const handalchange = async (pollId, userId, answer) => {
    if (userId === false || 0) {
      history.push("/signin");
    } else {
      console.log(pollId);
      console.log(userId); // getting
      console.log(answer); // getting
      await axios
        .post(`${API}/vote/${pollId}`, { userId, answer })
        .then((data) => {
          if (data.error) {
            seterror(data.error);
            console.log(data.error);
          } else {
            loadPoll();
            // console.log(data);
          }
        });
    }
  };

  const errorMessage = () => {
    return (
      <div className="">
        <div className="">
          <div
            className="alert alert-danger"
            style={{ display: error ? "" : "none" }}
          >
            {error}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="">
      <div className="container my-5">
        <h1 className="blog_heading my-3">Poll's of the Day</h1>
        <div className="row">
          {errorMessage()}
          {polls.reverse().map((poll, index) => (
            <div className="col-lg-4 col-12 gy-3">
              <div className="card poll_card" key={index}>
                <div className="card-body">
                  <Poll
                    question={poll.question}
                    answers={Object.keys(poll.options).map((key) => {
                      return {
                        option: key,
                        votes: poll.options[key].length,
                      };
                    })}
                    onVote={
                      (answer) =>
                        handalchange(
                          poll._id,
                          userId,
                          answer,
                          console.log(answer)
                        ) // getting vote
                    }
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default FullPoll;

这是我得到的前端结果..! enter image description here 这是我的第二页,我也得到了相同代码的结果......!

import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import "../../styles.scss";
import { Link } from "react-router-dom";
import { isAutheticated } from "../../auth/helper/index";
import { getPolls, postPoll } from "../helper/coreapicalls";
import axios from "axios";
import { API } from "../../backend";
import { useHistory } from "react-router-dom";

const MainPoll = () => {
  const userId = isAutheticated() && isAutheticated().user._id;
  const [polls, setPoll] = useState([]);
  const [error, seterror] = useState(false);
  const history = useHistory();
  useEffect(() => {
    loadPoll();
  }, [polls]);

  const loadPoll = () => {
    getPolls().then((data) => {
      if (data.error) {
        seterror(data.error);
      } else {
        setPoll(data.reverse());
        console.log(data);
      }
    });
  };

  // Handling user vote
  // Increments the votes count of answer when the user votes
  const handalchange = async (pollId, userId, answer) => {
    if (userId === false || 0) {
      history.push("/signin");
    } else {
      console.log(pollId);
      console.log(userId); // getting
      console.log(answer); // getting
      await axios
        .post(`${API}/vote/${pollId}`, { userId, answer })
        .then((data) => {
          if (data.error) {
            seterror(data.error);
            console.log(data.error);
          } else {
            loadPoll();
            // console.log(data);
          }
        });
    }
  };

  return (
    <div className="">
      <div className="container ">
        <h1 className="blog_heading">Poll's of the Day</h1>
        <div className="row PollsHeight">
          {polls.reverse().map((poll, index) => (
            <div className="col-lg-4 col-12 gy-3">
              <div className="card poll_card" key={index}>
                <div className="card-body">
                  <Poll
                    question={poll.question}
                    answers={Object.keys(poll.options).map((key) => {
                      return {
                        option: key,
                        votes: poll.options[key].length,
                      };
                    })}
                    onVote={
                      (answer) =>
                        handalchange(
                          poll._id,
                          userId,
                          answer,
                          console.log(answer)
                        ) // getting vote
                    }
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
        <Link to="/allpolls" className="ForMorebtn container">
          For More
        </Link>
      </div>
    </div>
  );
};

export default MainPoll;

这是我第二页的前端结果! enter image description here 我只想连接两个页面,如果我在第一页上投票,结果将反映在第二页上......!不仅仅是一个页面上......!

【问题讨论】:

    标签: javascript node.js reactjs react-native


    【解决方案1】:

    我认为你可以使用 window.localStorage 来做到这一点。

    类似于当您选择值时保存选项和商店。

    localStorage.setItem('option', 'option1');
    

    然后,当您显示选择时,您可以验证存储是否为空或具有某些值:

    const cat = localStorage.getItem('option');
    

    并且根据选项,您可以显示该值。

    你也可以用 Redux 来做,会复杂一些。

    您可以在此处阅读有关 Window.Localstorage 的更多信息:

    https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

    【讨论】:

    • 谢谢!但是你能告诉我代码吗..!实际上我不明白我可以在哪里更改我的代码@Carlos
    猜你喜欢
    • 2017-09-20
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多