Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【2022.8.25】useState #65

Open
lkzwc opened this issue Aug 29, 2022 · 0 comments
Open

【2022.8.25】useState #65

lkzwc opened this issue Aug 29, 2022 · 0 comments
Labels

Comments

@lkzwc
Copy link
Owner

lkzwc commented Aug 29, 2022

useState

首先useState会返回一个最新值和一个修改值的方法,参数传入的是一个默认值

function myuseState1( initValue){

  let value = initValue
 function setValue(newValue){
    value = newValue
 }
 return [ value,setValue]
}
function myuseState2( initValue){
  const getter=()=>initValue
  const setter=(value)=>(initValue =value )
 return [getter,setter]
}

如果定义多个useState呢?

用数组保存呗

let index =0
let stateArr =[]

function useState(initvalue){
   stateArr[i] =  stateArr[i]  || initvalue

  let cunrrent = index  //保存对应的下标 执行setState直接更新对应的
 function setState(newValue){
   stateArr[current] = newValue
  render();
 }
  return [stateArr[index++],setState]
}

render(){
 index=0   // render的时候清空 从头开始
}



@lkzwc lkzwc added the react label Aug 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant