• 开源镜像
  • 开源沙龙
  • 媛宝
  • 猿帅
  • 注册
  • 登录
  • 息壤开源生活方式平台
  • 加入我们

开源日报

  • 2018年12月10日:开源日报第277期

    10 12 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《永续魔法卡——悬浮 pennywise》传送门:GitHub链接

    推荐理由:如果你想要一直看着某个窗口——在干着其他事情的时候,比如刷游戏的时候看一看新闻联播之类的,那么这个项目就能够帮上你的忙。它能够让你免受频繁切换的烦恼,一直将窗口悬浮在最顶部,只需要输入 URL,一切都会简单轻松。顺带一提,在一边写代码一边看教程的时候使用有奇效。


    今日推荐英文原文:《Want To Be In The Top 1% Of IT Teams? Here’s What It Takes》作者:Vishnu Datla

    原文链接:https://medium.com/devopslinks/want-to-be-in-the-top-1-of-it-teams-heres-what-it-takes-6f281b44b185

    推荐理由:在现在这个时代如果想要成为优秀的团队,速度是必不可少的

    Want To Be In The Top 1% Of IT Teams? Here’s What It Takes

    Recently, one of our client’s Chief Information Officer commented that he wanted his team to be in the top 1% in the industry.

    Soon after, our sponsor, their VP of IT, and I tried to unpack the CIO’s statements and get something tangible to help my customer deliver the CIO’s vision. We asked, what does it really take to reach that 99th percentile?

    In a word, speed.

    It wasn’t long ago that software companies could enjoy the luxury of moving slowly. Every two years, a new version of software would be released, CDs would be shipped to customers who would eagerly pop them into their disc drives and hit “install.”

    And then? The whole two-year process would start all over again.

    Today, however, if you want to be in the top 1% of IT teams, that approach is laughable, due to the new benchmarks of software delivery.

    Companies like Amazon, Facebook, Netflix, and Etsy have blazed the trail to get their code from a developer all the way to an end user on a daily basis. The only way to get there is by implementing DevOps, refining processes, staying competitive, and applying pragmatic leadership goals.

    It takes a ton of hard work, but if you’re passionate, strategic and confident enough, you’ll be able to pull it off.

    Here’s how to go about it:

    Grasp the importance of speed and agility.

    Increasing the delivery velocity is a business imperative.

    There have never been more tools and opportunities (along with online communities) to get help for those who want to move fast.

    Today, a broke college kid with access to open-source software can build an app along with e-commerce integration in weeks. As an IT leader, you need to be a passionate and hungry college kid. Moving quickly allows you to challenge the Goliaths of the industry that can’t react as fast.

    Take giants like Capital One and Bank of America, for example.

    For a random consumer in Minneapolis, there really isn’t much of a difference between the two banks in terms of their services. But the mobile app software is really what tips the scales. If Capital One’s app keeps giving customers new features that they demand regularly, those customers will begin to move more of their business over to that platform and away from the competition.

    It’s no longer beneficial to be quick, it’s actively detrimental to be slow. Any company that isn’t keeping pace is already on their way to extinction.

    Create a sense of urgency to stay competitive.

    Unfortunately, just understanding of the importance of velocity and speed is not enough.

    You have to increase your velocity, not just within your team but within some dependent functions, too. In the SaaS software business, I see a new competitor enter our market every quarter — and any one of them has the potential to hurt our market share. A competitor is always knocking at the door. If we lose focus, even for a short time, someone is going to come to take a bite out of my business.

    I know this from my own experience.

    At one point, moving slowly affected our growth at my startup, AutoRABIT.

    We were supporting several tech stacks with 100+ integrations, but we weren’t investing in DevOps or tools to support our platform with seven different modules (which are independent products in their own right).

    Due to our divided attention and slow processes, we lost leadership on a couple of modules. Another company built a better module than us, and we were consistently slow and struggling — and maybe bit complacent. In fact, we ended up partnering with our competitor, and we now refer business to them.

    While we have refocused and are revamping our core modules today, we lacked a sense of urgency and the 1% mindset we needed to be faster and nimbler.

    It was a wake-up call for me.

    Realize that Change Management is key.

    After our failure, I knew I had to start practicing what I was preaching when it came to DevOps and cultural change.

    The first thing we did was step back and spend time on planning. Our team began investing in training, tools, and processes, but most importantly in Change Management. We started automating and spending time and money on better processes, better people, better technology. We even increased our salary budgets to attract top talent and brought in a consulting firm to audit our process and service guidelines.

    We had to tackle:

    • Internal resistance to DevOps and culture changes.
    • External pressure created by our innovation goals versus the external stability needs.
    • Calculated risks in tools, new process, people churn, and the team’s breakpoints.

    It wasn’t an easy journey.

    But as a leader, you have to show your team what it means to be in the top 1%. You have to communicate the vision, the goals, and the way forward. You have to make sure every developer is getting better and enjoying what they do because you’ll only have success when your team is looking forward to coming into the office and achieving something every day, every week, and every month.

    That’s how a top 1% team is born.


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

  • 2018年12月9日:开源日报第276期

    9 12 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

     

    今日推荐开源项目:《GitHub 上什么都有.jpg lists》传送门:GitHub链接

    推荐理由:一个 GitHub 上各种列表的列表,你可以在这个列表中发现各种各样的事物(尽管它们中的有些非常……奇怪),从技术类的 React 各种工具,到非技术类的婴儿睡眠指南,再到列表的列表的列表的列表的列表的列表,最后一个我真的没打错不信可以去看看这个项目的最后面,真的是六个。

    或者可以直接通过这个链接直达:https://github.com/enedil/awesome-awesome-awesome-awesome-awesome-awesome


    今日推荐英文原文:《Five Python Tricks You Need to Know Today》作者:Enoch CK

    原文链接:https://towardsdatascience.com/five-python-tricks-you-need-to-learn-today-9dbe03c790ab

    推荐理由:使用 Python 时写代码的一些小技巧,兴许有些会对你有所帮助

    Five Python Tricks You Need to Know Today

    Whether you are a senior AI engineer or a first-year biology student, you will come across the Python programming language at some point. First released in 1991, Python has quickly become the favorite language used by programmers and technologists. Based on Stack Overflow question views in high-income countries, Python is found to be rapidly becoming the most popular language of choice.

    The Incredible Growth of Python– David Robinson

    Being a high-level, interpreted language with a relatively easy syntax, Python is perfect even for those who don’t have prior programming experience. Popular Python libraries are well integrated and used in diverse fields such as bioinformatics (biopython), data science (pandas), machine learning (keras/ tensorflow) and even astronomy (astropy). After learning C and Java as my first programming languages, I was able to teach myself Python within weeks of googling it. Despite executing much slower than Java and other languages, Python actually improves productivity by having well-built process integration features.

    Before we get started, I highly recommend you to check out Dan Bader’s Python Tricks Book. In his book, Dan has shared some really informative tips and tricks about how to code more efficiently in Python. If you do not know Python at all, I highly suggest you to get started with Code Academy’s Learn Python interactive course.


    Trick №1: Powerful One-Liners

    Are you tired of reading through lines of code and getting lost in conditional statements? Python one-liners might just be what you are looking for. For example, the conditional statements

    >>> if alpha > 7:>>>    beta = 999>>> elif alpha == 7:>>>    beta = 99>>> else:>>>    beta = 0

    can really be simplified to:

    >>> beta = 999 if alpha > 7 else (beta == 99 if alpha == 7 else 0)

    This is ridiculous! Should you pay more attention to the code you wrote, you’d always find places where you can simplify as one-liners. Besides conditional statements, for loops can also be simplified too. For example, doubling a list of integer in four lines

    >>> lst = [1, 3, 5]>>> doubled = [] >>> for num in lst:>>> doubled.append(num*2)

    can be simplified to just one line:

    >>> doubled = [num * 2 for num in lst]

    Of course, it might get a bit messy if you chain everything into one-liners. Make sure you aren’t overusing one-liners in your code, as one might argue that the extensive use of one-liners is “un-Pythonic”.

    >>> import pprint; pprint.pprint(zip(('Byte', 'KByte', 'MByte', 'GByte', 'TByte'), (1 << 10*i for i in xrange(5))))

    Trick №2: Quick String Manipulations

    String manipulations can be tricky (no pun intended), but Python has hidden shorthands to make your life significantly easier. To reverse a string, we simply add ::-1 as list indices

    >>> a =  "ilovepython" >>> print a[::-1] nohtypevoli

    The same trick can be applied to a list of integers as well. String manipulation is extremely easy in Python. For example, if you want to output a sentence using the following predefined variables str1 , str2 and lst3

    >>> str1 = "Totally">>> str2 = "Awesome">>> lst3 = ["Omg", "You", "Are"]

    Simply use the .join() method and arithmetic operators to create the desired sentence.

    >>> print ' '.join(lst3)Omg You Are>>> print ' '.join(lst3)+' '+str1+' '+str2Omg You Are Totally Awesome

    Besides string manipulation, I also recommend reading more about regex (regular expressions) to effectively search through strings and filter patterns.


    Trick №3: Nested Lists Combination

    itertools is probably one of my favorite Python library. Imagine your code had a dozen of lists and after some manipulation, you ended up with a deeply nested list. itertools is exactly what you need to resolve this syntactical mess.

    >>> import itertools>>> flatten = lambda x: list(itertools.chain.from_iterable(x))>>> s = [['"', 'An', 'investment'], ['in'], ['knowledge'], ['pays'], ['the', 'best'], ['interest."', '--'], ['Benjamin'], ['Franklin']]>>> print(' '.join(flatten(s)))" An investment in knowledge pays the best interest." -- Benjamin Franklin

    As you can see from the example above, we can combine nested lists and strings using .join() and itertools . .combinations() method in itertools is also a powerful tool to return the length subsequences of elements from the input iterable. Click here to read more about itertools .


    Trick №4: Simple Data Structures

    Going back to Trick №1, it is also very easy to use one-liner to initialize data structures in Python. Harold Cooper has implemented a one-liner tree structure using the following code:

    >>> def tree(): return defaultdict(tree)

    The code shown above simply defines a tree that is a dictionary whose default values are trees. Other one-liner functions such as prime number generator

    >>> reduce( (lambda r,x: r-set(range(x**2,N,x)) if (x in r) else r),         range(2,N), set(range(2,N)))

    can be found all over Github and Stack Overflow. Python also has powerful libraries such as Collections , which will help you to solve a variety of real-life problems without writing lengthy code.

    >>> from collections import Counter>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]>>> print(Counter(myList))Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})

    Trick №5: Printing Made Easy

    The last trick is something I wish I had known earlier. Turns out to print an array with strings as one comma-separated string, we do not need to use .join() and loops.

    >>> row = ["1", "bob", "developer", "python"]
    >>> print(','.join(str(x) for x in row))
    1,bob,developer,python

    This simple one-liner will do:

    >>> print(*row, sep=',')
    1,bob,developer,python

    Another neat printing trick is to make use of enumerate. enumerateis a built-in function of Python which is incredibly useful. So instead of writing a four-line code to print

    >>> iterable = ['a','b','c'] >>> c = 0 >>> for item in iterable: >>>  print c, item >>>  c+= 1 0 a 1 b 2 c

    The same can be done under just two lines

    >>> for c, item in enumerate(iterable): >>>  print c, item

    There are hundreds of thousands of printing tricks in Python such as pretty printing pprint. Comment below if you know a slick Python trick!


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/Opening

  • 2018年12月8日:开源日报第275期

    8 12 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

    今日推荐开源项目:《可爱即是正义 react-kawaii》传送门:GitHub链接

    推荐理由:唯有可爱才是永恒不变的正义,这个项目就是一个应用于 React 中的可爱组件集合,它最大的特点就是使用了非常多的弧线和表情让组件看起来非常圆滑,兴许你在使用 React 创建这样可爱风格的页面的时候可以考虑一下这些组件。

    表情和基础部件的组合:


    今日推荐英文原文:《Programmers and Managers》作者:Maksim Solovjov

    原文链接:https://medium.com/@maksimsolovjov/programmers-and-managers-868faa16d20f

    推荐理由:介绍了一本看起来非常不起眼的书——Programmers and Managers

    Programmers and Managers

    I did not expect much from this book. I bought it in one of those antique-book-buying binges, and now I can’t even remember who recommended it to me. For three pounds it was a bargain anyway.

    The previous owner was the Massachusetts Community College Library. The book had only one official reader: someone had to return it by the 6th of April, 1978.

    From the very first pages, I realised that I’m in for something unusual. The author was an anthropologist. He became interested in programmers as they became widespread, some even moving into his neighbourhood. (The book shows its age in noting that many were women.) Despite the proliferation of the profession, nothing much was written about the work relationship between programmers and their managers. If the topic was mentioned at all in some management literature, the portrayal of programmers was usually not flattering. So the author decided to fill the gap.

    Being an anthropologist, he studied each by observation, attempting to figure out what was really happening. That was hard. First, he identified that despite dozens of titles, he could partition all “software workers” into three groups: coders (technicians), programmers and analysts. Coders did least creative jobs, mostly just punching characters. Programmers worked on all aspects of writing a program, but in an organisation they could be further specialised. Their job, while more creative than that of coders, still involved a lot of routine. Analysts designed full systems and broke them into parts to be implemented by programmers. Their job was most loosely defined, since it often involved managerial and sales elements, and represented in microcosm internal conflicts present in many of the organisations.

    He then spotted that, as a trend, this division mimicked class divisions present in other engineering jobs. (Implying America has social classes in 1970’s is probably the most sure way to not get your book read…) Coders usually had little tertiary education. Programmers had vocational training from a community college. Analysts came from elite technical universities. This educational background correlated with the occupations of their parents. Generally, coders came from families of much more modest means compared to analysts.

    This division was not incidental. Initially, programmers resembled medieval crafters much more than white-collar engineering workers. Much of the training was done via a master/apprentice model. There were not many tools for separation of labour; programming was a complex artisan endeavour. This meant that the programmer you hired had to be skilled enough to solve any problem they might encounter.

    With the advent of structured programming and code modularisation, it became possible to split the work into parts of different complexity. You no longer had to maintain 5 highly-skilled specialists: one expert and 4 junior programmers would do. Much like in Adam Smith’s pin-making example, the latter team is also likely to be more productive overall.

    The author’s narrative on structured programming jarred my programmer ears. To his credit, he goes into great pains to affirm that yes, both programmers in general and Dijkstra et al., who created the technique, in particular, they see structured programming simply as a tool to do their job better. And yet, from the managerial perspective, it is a tool for process control. Structured programming allows to de-skill and routinise the work overall, bringing it closer to a factory model.

    I wish that was the only blow to my sense of self-importance… The author decided to investigate the real role of a programmer in an organisation. This was complicated by high salaries most programmers commanded, oftentimes placing them on-par with line-managers in terms of remuneration. However, the pay package came from the supply/demand imbalance, rather than essential status of the job within the organisation. For most organisations, a programmer was either a clerk — a person who does the job defined by a manager, or an engineer — a person hired by a manager to automate production process. Ultimately, the relationship was subservient.

    While he was at it, the author reminded that twentieth-century engineers are not the same breed as nineteenth-century ones, who much more resembled modern day small businessmen and managers. At least the progress wasn’t kind across the board.

    To rub some salt into my wounds, the author then went over techniques employed by managers to keep programmers happy and create a sense of career growth. From dual career ladders (where one can progress as an engineer or as a manager), out of which one is in practice always much shorter, to title changes without much difference in the essence of the work, to regular pay increments until you get fired — most of these are omnipresent in a modern software shop. In most of them, only managers get real career growth: they manage a team, then a product area, and then move to defining policies and no longer manage. The growth on the management ladder brings executive authority in allocating resources and pursuing business opportunities. The growth on the engineering ladder, once you are an analyst, at best brings more responsibility and accountability.

    (The author observed that the growth from coder to a programmer to an analyst is, in practice, also elusive. Often there are educational barriers associated with a higher position, effectively confining coders to coding. Not something I’ve ever observed directly, given that throughout most of my career my coworkers had stellar academic credentials or even PhDs. Yet, I’ve witnessed people denied promotion due to lack of education in traditional factories, so it’s not hard to believe that this is the case in many workplaces that employ software workers too.)

    Then there are tools for control. Chief of them is insisting on individualism and a perverse definition of “professionalism”. Individualism is routinely stressed in a workplace, for example, by insisting that pay information is private. Moreover, everyone is individually assessed. The fact that people square in their heads the belief in individual treatment with salary bands attests to incredible capacity of human mind for dealing with cognitive dissonance.

    This individualism is especially useful in case someone gets fired. Individual performance implies individual responsibility in such matters, so as far as most employees are concerned, any unfair treatment is an individual matter to sort out between the manager and the employee. This is something which I, unfortunately, was a witness of.

    The professionalism that is usually brought up is redefined to mean something else from what a real profession entails. A professional body is controlled by peers, who limit the entry into the field via certification. It is a descendant of a Medieval guild. That’s the exact opposite what an employer would want for software workers, since they are scarce as is. When the employers bring up the concept of “professionalism”, they usually mean doing what told without much fuss.

    As I finished the book, I found myself in a state of mild shock. I wanted to argue with the writer, and yet I could not. There was no explicit judgement of these events: while the author liked programmers, he did not state that cost optimisation is bad and that routinisation of work should stop, for example. He merely stated that it is happening, and programmers should better be aware of it.

    When I was in school, I made good money by building custom websites. Nowadays, creation of websites at that level is automated, routine, and doesn’t bring even a tenth of revenue it used to. Most people can do it themselves with a website builder. I never intended for this to be my profession, and moved on to more complex pastures. My skills became obsolete, but luckily for me, I no longer depended on them for living anyway.

    Yet, how many of such transformations can one do in their life? The author wrote that programmer’s career is short (unfortunately, he did not elaborate too much on his rhetorical question whether it is skills or salary that becomes obsolete). I wanted to disagree, but then again, recently I was asked for the third time, after someone witnessed my work environment, whether anyone over thirty works in my office. While the answer is definitely yes, this made me think.

    In a weird way, “Programmers and Managers” reminded me of the work of Thomas Malthus. He postulated that population growth is exponential while food growth is linear, and hence a catastrophe always comes to restore the balance between the population and resources. Just as he formulated this idea, industrial revolution kicked-in at full speed, and exponential productivity growth confined Malthusian world to the past. Yet, should the productivity growth stop, his reasoning might be relevant again.

    Similarly, “Programmers and Managers” made a lot of negative predictions, which did not materialise over the years. Due to ever-growing demands on the complexity of systems we want to build, the modern programmer was not entirely reduced to an assembly worker. But just like our capacity for productivity growth is not a given, neither is this insatiable demand for novel things to automate. When you are a programmer, obsolescence is always around the corner.

    Whether you are a programmer or a manager, I can’t recommend Philip Kraft’s “Programmers and Managers: The Routinization of Computer Programming in the United States” enough.


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

  • 2018年12月7日:开源日报第274期

    7 12 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《前端互动问答环节 Front-End-FAQ》传送门:GitHub链接

    推荐理由:在前端学习过程中遇上了不懂的问题?这个项目就是一个可以交流前端问题的平台,你可以在这里浏览别人提出的问题,也可以很简单的去提问或者回答补充里面的一些问题,在学习遇到困难时不妨来这里看看有没有人已经对你的问题作出了解答。


    今日推荐英文原文:《What is State in React?》作者:Dina Hafez

    原文链接:https://medium.com/@deedee8/what-is-state-in-react-7e4ba938df23

    推荐理由:介绍 React 中的与 State 有关的知识,推荐正在学习 React 的同学一读

    What is State in React?

    State is a JavaScript object that stores component’s dynamic data and it enables a component to keep track of changes between renders. Because state is dynamic, it is reserved only for interactivity so you don’t use it for static React projects.

    Components defined as classes have some additional features. Local state is exactly that: a feature available only to classes. State can only be used within a class and usually the only place where you can assign this.state is the constructor.

    class Greeting extends React.Component { constructor() { super(); this.state = { name: 'John Smith' } } render() { return <h1>Hello, my name is { this.state.name }</h1>; } }

    Nowadays you can use state without the constructor by using Property initializers which is a new feature came out in 2017.

    class Greeting extends React.Component { state = { name: 'John Smith' } } render() { return <h1>Hello, my name is { this.state.name }</h1>; } }

    State is managed within the component (similar to variables declared within a function). State in React Component is its own local state, which means the state cannot be accessed and modified outside the component and can only be used inside it, probably that will remind you of a function own local scope.

    What does setStatedo?

    setState() schedules an update to a component’s state object. When state changes, the component responds by re-rendering.

    Using State Correctly

    • Do Not Modify State Directly
    • State Updates May Be Asynchronous
    • State Updates are Merged

    Do Not Modify State Directly

    Let’s start explaining one at a time. The first point requires not to modify state directly as it will not re-render a component like the following example:

    // Wrong
    this.state.comment = 'Hello';

    Instead you should use setState() like this:

    // Correct
    this.setState({comment: 'Hello'});

    And as I mentioned before the only place where you can assign this.state is the constructor.

    State Updates May Be Asynchronous

    React may batch multiple setState() calls into a single update for performance.

    Calls to setState are asynchronous when they are inside event handlers and that when you don’t rely on this.state to reflect the new value immediately after calling setState.

    incrementCount() {
      // Note: this will *not* work as intended.
      this.setState({count: this.state.count + 1});
    }
    
    handleSomething() {
      // Let's say `this.state.count` starts at 0.
      this.incrementCount();
      this.incrementCount();
      this.incrementCount();
      // When React re-renders the component, `this.state.count` will be 1, but you expected 3.
    
      // This is because `incrementCount()` function above reads from `this.state.count`,
      // but React doesn't update `this.state.count` until the component is re-rendered.
      // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.

    To fix it, use a second form of setState that accepts a function rather than an object to ensure the call always uses the most updated version of state.

    Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting:

    incrementCount() {
      this.setState((state) => {
        // Important: read `state` instead of `this.state` when updating.
        return {count: state.count + 1}
      });
    }
    
    handleSomething() {
      // Let's say `this.state.count` starts at 0.
      this.incrementCount();
      this.incrementCount();
      this.incrementCount();
    
      // If you read `this.state.count` now, it would still be 0.
      // But when React re-renders the component, it will be 3.
    }

    Also you can pass props as a second argument at the time the update is applied:

    // Correct
    this.setState((state, props) => ({
      counter: state.counter + props.increment
    }));

    State Updates are Merged

    When you call setState(), React merges the object you provide into the current state.

    For instance, your state may contain several independent variables:

    constructor(props) {
        super(props);
        this.state = {
          posts: [],
          comments: []
        };
      }

    Then you can update them independently with separate setState() calls:

    componentDidMount() {
        fetchPosts().then(response => {
          this.setState({
            posts: response.posts
          });
        });
    
        fetchComments().then(response => {
          this.setState({
            comments: response.comments
          });
        });
      }

    The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments.

    You might be asking what is ComponentDidMount() and how it is used. It is a method that is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. So if you need to load data from a remote endpoint (API), this is a good place to instantiate the network request.

    As you can see in the above example the properties for this.state are now independent and separately added this.setState , passed an object to each property and surrounded them by ComponentDidMount() where they will be added to the DOM tree after we get the response from the fetchPosts() and fetchComments().

    To read more about setState() check this link.


    The Data Flows Down

    Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn’t care whether it is defined as a function or a class.

    It is not accessible to any component other than the one that owns and sets it. That is why state is often called local or encapsulated.

    A component may choose to pass its state down as props to its child components.

    This also works for user-defined components:

    <FormattedDate date={this.state.date} />

    The FormattedDate component would receive the date in its props and wouldn’t know whether it came from the Clock’s state, from the Clock’s props, or was typed by hand:

    function FormattedDate(props) {
      return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
    }

    This is commonly called a top-down or unidirectional data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.

    Components are truly isolated and are updated independently.

    State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Though you need to work with state for interactive apps, you should avoid using many Stateful Components.


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

←上一页
1 … 190 191 192 193 194 … 262
下一页→

Proudly powered by WordPress