【发布时间】: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