我有一个呈现链接的哑组件。我有一个简单的三元检查,如果道具props.filter
与其props.filterType
相同,那么它将呈现<span>
而不是<a>
标记。
这个哑组件从父组件传递filter
,该组件连接到Redux存储。
我遇到的错误是:我的父组件确实接收到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;
我认为我对无状态功能组件的理解存在巨大漏洞。任何帮助或建议或指示将不胜感激。
谢谢,
答案 0 :(得分:2)
你实现无状态组件是错误的。它应该进行渲染,而不是使用render
方法返回对象。
const FilterLink = props => {
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>
);
};