1
我正在学习reactjs的生命周期方法。为了深入理解,我试图通过创建自我榜样来学习。我做的是,我做了一个叫做颜色的对象,我把它们传递给ColorButtons组件。颜色对象被提取以显示基于道具中颜色的按钮。我可以显示按钮,但是当我点击时,让我们说#fd5c63颜色按钮,应该发生一些事件。如果我再次点击相同的按钮,则不应该重新渲染页面。如果我是对的,我必须使用componentWillRecieveProps和shouldComponentUpdate。这就是为什么我想深深理解他们。如果我对重新渲染部分的理解是正确的,为什么我的componentWillRecieveProps没有在控制台中显示任何东西?任何人都可以请帮我理解我正在谈论的情景吗?nextProps没有显示在我的componentWillRecieveProps
这里是我的代码
const colors = [
{id:1, color: '#00a98f'},
{id:2, color: '#fd5c63'},
{id:3, color: '#49176d'}
];
render(<ColorButtons colors = {colors} />, document.querySelector('#app'))
class ColorButtons extends React.PureComponent {
constructor(props) {
super(props);
}
componentWillReceiveProps(nextProps) {
console.log(`nextProps ${nextProps}`);
}
render() {
const colorBtn =() => this.props.colors.map((color, i) =>
<ColorButton
color={color.color}
key={color.id}
onClick={()=>console.log(color.color)}
/>
);
return (
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
{colorBtn()}
</Wrapper>
)
}
}
export default ColorButtons;
这是工作示例
https://www.webpackbin.com/bins/-Kif7NlLz5BCDXQ18fyg
什么问题?代码的工作原理与上述相同,并记住在初始安装时不会调用“componentWillReceiveProps”。只有当装载的组件获取新的道具时才会调用它,而不是在状态更改和组件重新显示时调用。 – Li357