【问题标题】:React state always one step behind when getting cookie获取 cookie 时反应状态总是落后一步
【发布时间】:2020-01-20 10:00:44
【问题描述】:

我有一个组件可以在浏览器中显示电子邮件 cookie 的值,但如果您在 URL 中传递新电子邮件,它应该会更新。

目前,如果我在 URL 中传递一封新电子邮件,我可以看到 cookie 已更新,但新电子邮件未呈现在页面上,仅显示前一个。

import React from "react";
import Helper from "plugins/helper";

class emailField extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      cookie: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.updateCookie = this.updateCookie.bind(this);
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.cookie !== this.state.cookie) {
      this.updateCookie();
      return true;
    }
    return false;
  }

  componentDidMount() {
    this.updateCookie();
  }

  updateCookie() {
    const cookie = Helper.getCookie("email");
    const query = window.location.href;
    const emailUrl = query.match(/email=/g);
    if (cookie && emailUrl) this.setState({ cookie });
  }

  handleChange(e) {
    Helper.setCookie("email", e.target.value);
  }

  render() {
    const { cookie } = this.state;
    const { id } = this.props;
    return (
      <div id={id}>
        <div className="row noEmailUrl" style={{ display: "none" }}>
          <div className="col-md-2"></div>
          <div className="col-md-10">
            <input
              className="email form-control emailPrimary"
              placeholder="Please enter your email address"
              name="EMAIL_ADDRESS_"
              value={cookie}
              onChange={this.handleChange}
            />
          </div>
        </div>
        <div className="row emailUrl">
          <div className="col-md-8 emailAddress">
            <span className="email">{cookie}</span>
          </div>
          <div className="col-md-4 editBtn">
            <button type="button" className="changeAddress">
              Edit email
            </button>
          </div>
        </div>
      </div>
    );
  }
}

export default emailField;

emailField.defaultProps = {
  id: " "
};

【问题讨论】:

    标签: reactjs cookies


    【解决方案1】:

    您正在做的是检查状态以查看是否需要更新状态。

    您只需调用一次updateCookie,因为它不依赖于组件中的任何内容。

    删除您的 shouldComponentUpdate 覆盖,因为它是不必要的(而且还有害 - 它会减慢渲染速度并有副作用,这是不应该的)。

    【讨论】:

    • 谢谢,我已经删除了,但我还是有同样的问题。如果我在 URL 中传递一封新电子邮件,它仍会显示上一封电子邮件,直到我再次刷新页面,它才会更新为新电子邮件。
    • 路由用什么?反应路由器?还有什么?
    【解决方案2】:

    如果我在 URL 中传递新电子邮件,我可以看到 cookie 已更新 但是新的电子邮件没有呈现在页面上,只有上一个 显示。

    我猜这意味着您想从 URL 查询字符串加载电子邮件,对吧? 但我有点困惑,因为您提供的代码仅从 cookie 加载数据。 如果您想同步来自 URL 的输入并将值保存到 Cookie,您可以尝试这样的操作。 但我认为我们应该只需要一个地方来保存电子邮件数据(URL 查询字符串或 cookie)。 希望这可以提供一些帮助。

    import React, { Component } from "react";
    import Cookies from "js-cookie";
    
    const COOKIE_KEY = "email";
    
    export default class CookieInput extends Component {
      constructor(props) {
        super(props);
    
        this.state = {
          email: this.getInitialStateFromCookie()
        };
      }
    
      getInitialStateFromCookie = () => {
        // if we have email in query string, then set as initial data
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has("email")) {
          const email = urlParams.get("email");
          Cookies.set(COOKIE_KEY, email);
    
          return email;
        }
    
        // otherwise, try get data from cookie
        return Cookies.get(COOKIE_KEY) || "";
      };
    
      handleChange = e => {
        const email = e.target.value;
    
        // update state, cookie & route when input change
        this.setState({ email });
        Cookies.set(COOKIE_KEY, email);
        window.history.pushState(null, null, `?email=${email}`);
      };
    
      render() {
        const { email } = this.state;
    
        return (
          <div>
            <input value={email} onChange={this.handleChange} />
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 2021-05-01
      • 2022-06-28
      • 2020-02-29
      • 1970-01-01
      • 2021-07-12
      • 2021-06-04
      相关资源
      最近更新 更多