【发布时间】:2017-08-25 04:15:25
【问题描述】:
我有一个呈现链接的哑组件。我有一个简单的三元检查道具props.filter 是否与其props.filterType 相同,然后它将呈现<span> 而不是<a> 标签。
这个哑组件是从连接到 Redux 存储的父组件传递的filter。
我遇到的错误是:我的父组件确实收到了filter 的更改/更新,我正在控制台记录它并且能够在父组件filter 中看到它确实发生了变化。
但是在我的愚蠢组件中,我是 console.logging props.filter,它根本没有改变。另一方面,使用 React 开发工具并检查组件并检查其道具,它确实发生了变化。什么?!
将无状态功能组件更改为类确实有效。将组件作为一个类的console.log(props.filter) 确实发生了变化。
这里是组件的代码,既是一个无状态函数又是一个类:
import React from 'react';
import './styles.css';
/* props.filter DOES CHANGE HERE */
class FilterLink extends React.Component {
render() {
console.log('this.props.filter: ', this.props.filter);
console.log('this.props.filterType: ', this.props.filterType);
console.log(this.props.filter === this.props.filterType);
return (
this.props.filter === this.props.filterType ?
<span className='active-link'>{this.props.children}</span>
:
<a id={this.props.filterType} className='link' href='' onClick={this.props.setFilter}>
{this.props.children}
</a>
);
}
};
/* props.filter DOESN'T CHANGE HERE */
const FilterLink = props => ({
render() {
console.log('props.filter: ', props.filter);
console.log('props.filterType: ', props.filterType);
console.log(props.filter === props.filterType);
return (
props.filter === props.filterType ?
<span className='active-link'>{props.children}</span>
:
<a id={props.filterType} className='link' href='' onClick={props.setFilter}>
{props.children}
</a>
);
},
});
export default FilterLink;
我认为我对无状态功能组件的理解存在巨大漏洞。任何帮助、建议或指导将不胜感激。
谢谢,
【问题讨论】: