【问题标题】:Conditional Rendering not reliably setting state on different components条件渲染不能可靠地在不同组件上设置状态
【发布时间】:2018-08-29 04:30:55
【问题描述】:

我想在某些页面上呈现两个导航按钮(浅色版和深色版)。

我尝试在构造函数中设置状态,并根据页面路径生成图片链接,但有时会生成错误的图片链接。似乎它正在根据曾经生成的第一页获取状态。例如,如果“主页”应该有按钮的轻量版,我点击的任何其他链接都会生成轻量版的标志,除非我刷新。如果“关于”应该有深色版本的标志,那么我点击的所有其他页面都会有深色版本,除非我刷新。

为什么在自然点击和浏览不同页面时不能正确生成?

MenuButton.js

import React, { Component } from 'react'; 

export default class MenuButton extends Component {

  constructor() {
    super();
    this.state = {
      logo_url: ''
    }
  }

  componentDidMount() {
    let currentPath = window.location.pathname;

    if (!currentPath.includes('about') && !currentPath.includes('news') 
        && !currentPath.includes('work')) {
          this.setState({ logo_url: `${require('../../assets/nav/logo-light.svg')}` });
    } else {
      this.setState({ logo_url: `${require('../../assets/nav/logo-dark.svg')}` });
    }
  }

  render() {
    return (
      <div className="menu-btn--cntr">
        <img src={this.state.logo_url} />
      </div>
    )
  }
}

【问题讨论】:

  • componentDidMount 只被调用一次。试试componentWillReceiveProps生命周期方法。
  • @PrakashSharma 当我将方法更改为 componentWillReceiveProps 时,根本没有渲染任何东西......
  • 你必须同时拥有 componentDidMount 和 componentWillReceiveProps
  • @bluebrooklynbrim 对于初始渲染,您还需要保留componentDidMount,因为对于初始渲染,不会调用componentWillReceiveProps

标签: javascript reactjs react-router


【解决方案1】:

您不需要使用状态和生命周期。

你可以试试下面的方法-

import React, { Component } from 'react'; 

export default class MenuButton extends Component {

  constructor() {
    super();
    this.state = {
      logo_url: ''
    }
  }

  getButton() {
    let currentPath = window.location.pathname;
    let btnUrl = ''; // or set some default 
    if (!currentPath.includes('about') && !currentPath.includes('news') 
        && !currentPath.includes('work')) {
          // this.setState({ logo_url: `${require('../../assets/nav/logo-light.svg')}` });
            btnUrl = `${require('../../assets/nav/logo-light.svg')}`;
    } else {
      // this.setState({ logo_url: `${require('../../assets/nav/logo-dark.svg')}` });
      btnUrl = `${require('../../assets/nav/logo-light.svg')}`;
    }
    return btnUrl;
  }

  render() {
    const btnUrl = this.getButton();
    return (
      <div className="menu-btn--cntr">
        <img src={btnUrl} />
      </div>
    )
  }
}

【讨论】:

    猜你喜欢
    • 2019-02-18
    • 2019-09-16
    • 2023-03-09
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多