javascript - When would a react component not be a pure component? - Stack Overflow

just been reading this: .html#reactpureponentand trying to work out when would a function not return so

just been reading this: .html#reactpureponent

and trying to work out when would a function not return something pure?

surely if you give a ponent the same props/state then it will always return the same result?

just been reading this: https://reactjs/docs/react-api.html#reactpureponent

and trying to work out when would a function not return something pure?

surely if you give a ponent the same props/state then it will always return the same result?

Share Improve this question asked Jan 3, 2019 at 14:27 Red BaronRed Baron 7,70112 gold badges47 silver badges112 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

If your function ponent has any side effects, then it would not be a pure ponent. For example, reading the current time via Date.now() is a side effect. If that date is passed via prop, then you're fine. But React/JavaScript cannot guarantee that a function ponent doesn't have side effects.

Consider the following function ponents.

function Impure() {
  return <p>{Date.now()}</p>
}

function Pure(date) {
  return <p>{date}</p>
}

Imagine if you had a ponent that showed the weather and a background image of the sun if it's daytime and a background picture of the moon if it's night.

You would pass in the temperature, wind speed etc. through props, but you would display the correct image depending on the time of day.

So, if you pass the temperature of 15 degrees during the day and during the night, the ponent will look differently even though you have passed the same props.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744123683a4559517.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信