简体   繁体   English

为什么这个组件渲染两次?

[英]Why does this component render twice?

export const AppComponent =()=>{
console.log('rendered');
const parameter = 'apple:two,mango:three'
    .split(',')
    .reduce((accumulator, currentValue) => {
      const [key, value] = currentValue.split(':');
      accumulator[key] = value;
    }, {});
return <div/>
}

This component renders twice and throws an error.此组件呈现两次并引发错误。 I know that the error is due to their being no return statement in the reduce function.我知道错误是由于它们在 reduce 函数中没有 return 语句。 However what I don't understand is why does it render twice?但是我不明白的是为什么它渲染两次?

Further when I remove the accumulator[key] = value code it only renders once.此外,当我删除accumulator[key] = value代码时,它只呈现一次。 As far as I understand, a component can re-render only in four cases据我了解,一个组件只能在四种情况下重新渲染

  1. change in state状态变化
  2. change in props道具的变化
  3. forced render强制渲染
  4. parent re-renders.父级重新渲染。

In my case the parent doesn't re-render (I checked it by using a console.log in the parent component) and this component is stateless and no props have been passed to it.在我的情况下,父组件不会重新渲染(我通过在父组件中使用 console.log 检查了它)并且该组件是无状态的,并且没有传递给它的道具。 Could someone please explain this behavior?有人可以解释这种行为吗?

Problem is with your reduce method, you are not returning accumulator..问题在于您的 reduce 方法,您没有返回累加器..

const App=()=> {
  console.log("rendered");
  const parameter = 'apple:two,mango:three'
    .split(',')
    .reduce((accumulator, currentValue) => {
      const [key, value] = currentValue.split(':');
      accumulator[key] = value;
      return accumulator; // this line should fix
    }, {});
  return(<div>hello</div>);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM