Skip to main content

Props vs State, Why?

Vì sao lại cần Props và State

Khi người ta tạo ra các component, họ mới đặt câu hỏi làm sao để các component giao tiếp với nhau (từ parent tới child). Nên người ta mới nghĩ ra props (properties) để truyền data. Props là read-only, không thể thay đổi hay tác động (immutable)

Nhưng khi một component cần react, render tùy theo tác động trực tiếp vào nó, nó cần data riêng để thể hiện sự thay đổi đó, nên người ta nghĩ ra sẽ cho component state (trạng thái) để thể hiện điều đó. State chỉ có thể update bởi chính component đó, bên ngoài không thể tác động

Comments

Popular posts from this blog

Closures

Closures is (a fancy term for) a function that remembers outside things that are used inside const createPrinter() {   const name = 'Alex'   const printName = () => {     console.log(name)   }   return printName } const myPrinter = createPrinter() myPrinter() // Alex This function that was return from from createPrinter function is called a closure . // Here is printName Closure is a combination of a function and the environment where it was declared .

React Asynchronous setState

setState is asynchronous action - If you need to use the updated state to do something, you should use a callback function in setState , so it will call after the state is updated: this.setState({data: newData}, () => console.log(this.state.data)) - If you wanna update the state with anything else, for example, set the '"title" to be "Hello", you can use the object in setState function, like this: this.setState({title: 'Hello'}) - But if you have to take the current state and use it to evaluate what to update, you should pass a function to setState function, so you will have access to the previous state and previous props. It will guarantees that you always get the latest update of the state or props: this.setState((prevState, prevProps) => {     return {count: prevState.count + 1}   } )

Array.fill()

Caveat: If you .fill() an Array with an object, all elements refer to the same instance (i.e., the object isn’t cloned) So if you do something like: let a = Array(3).fill([]) // create an array named a and fill it with 3 empty array a[2].push('poop') // push new value to the element array at index 2 expect [ [], [], [2]] But because all element refer to the same instance, so the result is: [[2], [2], [2]] More details here:  https://2ality.com/2018/12/creating-arrays.html