Publish to my blog (weekly)

    • 상태는 평범한 객체나 배열이면 충분히 다룰 수 있지만 리듀서에서 상태를 변경하지 않는 것을 강력히 권장합니다.
    • 스토어나 리듀서는 애플리케이션 코드가 직접 데이터를 조작하는 대신 액션이라고 불리는 평범한 객체로만 모든 데이터 변화를 묘사하도록 강제합니다.
    • 리듀서에서는 항상 새로운 객체를 반환해야합니다.
    • Flux와 또 다른 중요한 차이점은 Redux는 당신이 결코 데이터의 상태를 바꾸지 않는다고 가정한다는 점입니다.
    • 순수하지 않은 리듀서 구현은 시간 여행, 기록/재생, 핫 로딩과 같은 개발 지원 기능을 망가뜨립니다.
    • A component takes in parameters, called props
    • returns a hierarchy of views to display via the render method.
    • let's try passing some data from the Board component to the Square component.
    • value={i}
    • {this.props.value}
    • React components can have state by setting this.state in the constructor, which should be considered private to the component. Let's store the current value of the square in state, and change it when the square is clicked.
    • this.state = {  value: null,  };
    • this.setState({value: 'X'})
    • {this.state.value}
    • Whenever this.setState is called, an update to the component is scheduled, causing React to merge in the passed state update and rerender the component along with its descendants.
    • what the current state of each Square is.
    • Instead, the best solution here is to store this state in the Board component instead of in each Square – and the Board component can tell each Square what to display, like how we made each square display its index earlier.
    • When you want to aggregate data from multiple children or to have two child components communicate with each other, move the state upwards so that it lives in the parent component. The parent can then pass the state back down to the children via props, so that the child components are always in sync with each other and with the parent.
    • Pulling state upwards like this is common when refactoring React components
    • this.state = {  squares: Array(9).fill(null),  };
    • Modify it to pass a value prop to Square.
    • return <Square value={this.state.squares[i]} />;
    • Since component state is considered private, we can't update Board's state directly from Square.
    • The usual pattern here is pass down a function from Board to Square that gets called when the square is clicked. Change renderSquare in Board again so that it reads:
    • onClick={() => this.handleClick(i)}
    • We split the returned element into multiple lines for readability, and added parens around it so that JavaScript doesn't insert a semicolon after return and break our code.
    • onClick={() => this.props.onClick()}
    • when the square is clicked, it calls the onClick function that was passed by Board
    • handleClick(i) {  const squares = this.state.squares.slice();  squares[i] = 'X';  this.setState({squares: squares});  }
    • We call .slice() to copy the squares array instead of mutating the existing array. Jump ahead a section to learn why immutability is important.
    • Square no longer keeps its own state; it receives its value from its parent Board and informs its parent when it's clicked. We call components like this controlled components.
    • var newPlayer = Object.assign({}, player, {score: 2});
    • object spread syntax proposal
    • var newPlayer = {...player, score: 2};
    • Easier Undo/Redo and Time Travel#
    • Tracking Changes
    • Determining When to Re-render in React
    • Since immutable data can more easily determine if changes have been made it also helps to determine when a component requires being re-rendered.
    • shouldComponentUpdate()
    • We've removed the constructor, and in fact, React supports a simpler syntax called functional components for component types like Square that only consist of a render method. Rather than define a class extending React.Component, simply write a function that takes props and returns what should be rendered.
    • function Square(props) {  return (  <button className="square" onClick={props.onClick}>  {props.value}  </button>  ); }
    • Many components in your apps will be able to be written as functional components: these components tend to be easier to write and React will optimize them more in the future.
    • You'll need to change this.props to props
    • onClick={props.onClick}
    • squares[i] = this.state.xIsNext ? 'X' : 'O';
    • xIsNext: !this.state.xIsNext,
    • if (calculateWinner(squares) || squares[i]) {  return;  }
    • value={this.props.squares[i]}  onClick={() => this.props.onClick(i)}
    • <Board  squares={current.squares}  onClick={(i) => this.handleClick(i)}  />
    • But from now on, we will use ES6. ;)
       Let’s check out the same component in ES6:

       
      class HelloComponent extends React.Component {     render() {     return <div>Hello {this.props.name}</div>;   } }
    • render () {  return <div>Hello {this.props.name}</div>;  }
    • P allows the programmer to specify the system as a collection of interacting state machines, which communicate with each other using events.
    • P is a language for asynchronous event-driven programming.
    • P unifies modeling and programming into one activity for the programmer.
    • P has been used to implement and validate the USB device driver stack that ships with Microsoft Windows 8 and Windows Phone. P is also suitable for the design and implementation of networked, embedded, and distributed systems.
      • The class is an Akka actor which works in the following way:

        • a new instance of the actor is created when a file needs to be downloaded and the actor receives a message
        • the actor stores the reference to the sender
        • it sends a HTTP request to a service, responses are delivered as messages to the same actor
        • the actor can receive either the whole response or a chunk. If it has received a chunk the actor keeps storing the data in a byte array until the whole file is delivered
        • finally, when the actor has the whole response, it sends the response to the original caller (using the reference stored in step 2)
      • Conclusion

        • Do not forget about references stored internally by the actor system.
        • When you want to get rid of an Akka actor, simply stop it (if you do not keep any references to the actor instance).
        • Some of the actors you create may not be reusable. They won’t magically disappear, you have to remove them.
    • This code results in a TypeError because this.setState is not a function. This is because when the callback to the promise is called, the internal context of the function is changed and this references the wrong object.
    • For now you can think of a context as a box that you can put a value in:
    • you apply a function to this value
    • This is the idea that Functors,
    • you'll get different results depending on the context.
    • Applicatives, Monads
    • This is where fmap comes in.
    • fmap knows how to apply functions to values that are wrapped in a context.
    • A Functor is any data type that defines how fmap applies to it.
    • fmap magically applies this function, because Maybe is a Functor.
    • instance Functor Maybe where  fmap func (Just val) = Just (func val)  fmap func Nothing = Nothing
    • Now it makes sense why the Maybe data type exists.
    • If findPost returns a post, we will get the title with getPostTitle. If it returns Nothing, we will return Nothing
    • <$> is the infix version of fmap, so you will often see this instead:

       
      getPostTitle <$> (findPost 1)
    • Lists are functors too!
    • instance Functor [] where  fmap = map
    • When you use fmap on a function, you're just doing function composition!
    • With an applicative, our values are wrapped in a context, just like Functors:
    • But our functions are wrapped in a context too!
    • Using <*> can lead to some interesting situations.
    • > [(*2), (+3)] <*> [1, 2, 3] [2, 4, 6, 4, 5, 6]
    • Functors apply a function to a wrapped value:
    • Applicatives apply a wrapped function to a wrapped value:
    • Monads have a function >>= (pronounced "bind") to do this.
    • Monads apply a function that returns a wrapped value to a wrapped value.
    • class Monad m where
    • So Maybe is a Monad:
    • So now we know that Maybe is a Functor, an Applicative, and a Monad.
    • IO monad:
    • getLine
    • getLine :: IO String
    • readFile
    • readFile :: FilePath -> IO String
    • putStrLn
    • putStrLn :: String -> IO ()
    • All three functions take a regular value (or no value) and return a wrapped value.
    • getLine >>= readFile >>= putStrLn
    • Haskell also provides us with some syntactical sugar for monads, called do notation:
    • A functor is a data type that implements the Functor typeclass.
    • An applicative is a data type that implements the Applicative typeclass.
    • A monad is a data type that implements the Monad typeclass.
    • A Maybe implements all three, so it is a functor, an applicative, and a monad.
    • functors: you apply a function to a wrapped value using fmap or <$>
      • applicatives: you apply a wrapped function to a wrapped value using <*> or liftA
      •  
      • monads: you apply a function that returns a wrapped value, to a wrapped value using >>= or liftM
    • When using with transpiling loaders (like babel-loader), make sure they are in correct order (bottom to top). Otherwise files will be check after being processed by babel-loader

       
      module.exports =// ...   module: {     rules: [       {         test: /\.js$/,         exclude: /node_modules/,         use:"babel-loader""eslint-loader",         ],       },     ],   },   // ... }
    • {  "globals": {  "document": true,  "foo": true,  "window": true  } }
    • Works with or without Babel (you can remove react-hot-loader/babel from .babelrc and instead add react-hot-loader/webpack to loaders)

Posted from Diigo. The rest of my favorite links are here.

댓글

이 블로그의 인기 게시물

Publish to my blog (weekly)

Publish to my blog (weekly)