亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 vanilla JS 復制 useState

如何使用 vanilla JS 復制 useState

皈依舞 2023-07-20 16:05:04
Vanilla JS 中的代碼的實現是什么,它允許我們像 React 中的 useState 那樣聲明和更新狀態:const [x, setX] = useState(12);setX(14);console.log(x); // 14這道題嚴格來說是get better at JS。天真地說,這樣搭配是有意義的:// Solution 1function update(value, newValue) {    value = newValue;    return value;}function state(value) {    return [ value, update ];}let [value, setValue] = state(12)value = setValue(value, 14)console.log(value); // 14// Solution 2class State {    constructor(value) {        this.value = value;    }        update(newValue) {        this.value = newValue;    }}const x = new State(12);x.update(14);console.log(x.value); // 14但我不明白數組 [x, setX] 如何有一個回調(setX),當用 const 聲明時會影響 x ?我希望這是有道理的。
查看完整描述

5 回答

?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

我也想學習如何實現這一目標。我重構了代碼以使用箭頭函數,這會使代碼片段更難以閱讀和理解。如果是這種情況,請訪問上面鏈接中共享的資源。

這是實現:


const useState = (defaultValue) => {

? // ?? We create a function useState with a default value

? let value = defaultValue;

? // ?? We create a local variable value = defaultValue

? const getValue = () => value

? // ?? We create a function to set the value with parameter newValue

? const setValue = newValue => value = newValue // ?? We change the value for newValue

? return [getValue, setValue]; // ?? We return an array with the value and the function

}


const [counter, setCounter] = useState(0);

// ?? We destructure the array as a return of the useState function into two value


console.log(counter()); // ?? returns 0 which it's the value of counter()

我添加了注釋以便于理解。這是沒有注釋的實現:


const useState = (defaultValue) => {

? let value = defaultValue;

? const getValue = () => value

? const setValue = newValue => value = newValue

? return [getValue, setValue];

}


const [counter, setCounter] = useState(0);


console.log(counter());

為了更好地閱讀和理解,我使用常規函數包含了代碼片段:


function useState(defaultValue) {

? let value = defaultValue


? function getValue() {

? ? return value

? }


? function setValue(newValue) {

? ? value = newValue

? }


? return [getValue, setValue];

}


const [counter, setCounter] = useState(0);


查看完整回答
反對 回復 2023-07-20
?
浮云間

TA貢獻1829條經驗 獲得超4個贊

您缺少一些非常重要的東西 - 所有反應鉤子都使用一些“支持”它們的東西,當您沒有實例時,您只有一個函數,這允許您提供有效的實例變量。


React 中的這個東西被稱為 Fiber,它有效地代表了 React 組件的生命周期 - 它本身并不依賴于函數本身,它依賴于 React 正在渲染(和重新渲染)的組件。這就是為什么你可以有一個功能組件聲明,多次渲染同一個函數,并且每個函數都能夠維護自己的狀態 - 狀態不是函數的一部分,狀態是 React Fiber 的一部分。


但我不明白數組 [x, setX] 如何有一個回調(setX),當用 const 聲明時會影響 x ?


當你調用 時,你并不是簡單地改變 x 的值setX,你所做的是告訴 React 使用新的 x 值重新渲染組件(纖程)。


編輯:


一個非常簡單的示例,其中函數本身用作狀態的支持實例(React 中不是這種情況)可能如下所示:


// this line is example only so we can access the stateSetter external to the function

let stateSetter;


const states = new Map();


const useState = (value,context) => {

    const dispatch = v => {

            const currentState = states.get(context.callee);

            currentState[0] = typeof v === 'function' ? v(currentState[0]) : v        

            // we re-call the function with the same arguments it was originally called with - "re-rendering it" of sorts...

            context.callee.call(context);    

    }

    const current = states.get(context.callee) || [value,dispatch];

    states.set(context.callee,current);

    return current;


}


const MyFunction = function(value) {

    const [state,setState] = useState(value, arguments)

    stateSetter = setState;

    console.log('current value of state is: ',state)

}


MyFunction(10);

MyFunction(20); // state hasn't changed

stateSetter('new state'); // state has been updated!


查看完整回答
反對 回復 2023-07-20
?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

1.- 函數返回值的解構。

  • 我們應用它來解構函數返回的數組的兩個值。

  • 第一個值將返回變量的當前數據,第二個值將具有該值的更改函數。

// Main function useState (similar to react Hook)

function useState(value){

  // Using first func to simulate initial value

  const getValue = () => {

    return value;

  };


  // The second function is to return the new value

  const updateValue = (newValue) => {

    // console.log(`Value 1 is now: ${newValue}`);

    return value = newValue;

  };


  // Returning results in array

  return [getValue, updateValue];

}


// Without destructuring

const initialValue = useState(3);

const firstValue = initialValue[0];

const secondValue = initialValue[1];


// Set new data

console.log("Initial State", firstValue()); // 3

console.log("Final", secondValue(firstValue() + 5)); // 8


console.log("===========================");


// With destructuring

const [counter, setCounter] = useState(0);

console.log("Initial State", counter()); // 0

setCounter(counter() + 20);

console.log("Final", counter());


查看完整回答
反對 回復 2023-07-20
?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

class useState {

    constructor(defaultt=""){ 

        this.state = { value: defaultt}

        const handler = {

                set: () => {

                    return false

                }

            }

        const data = new Proxy(this.state,handler);

        const stateBind = this.setState.bind(this)

        return [data, stateBind];

    }

    setState(variable){

        this.state.value = variable

    }

}


const [like,setLike] = new useState(0)

console.log(like.value) // 0

like.value=2;

console.log(like.value) // 0

setLike(like.value + 1) 

console.log(like.value) // 1


查看完整回答
反對 回復 2023-07-20
?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

一個簡單的解決方案來模擬useState()使用構造函數。這可能不是最好的解決方案,因為構造函數每次都會返回函數的副本,但可以解決所討論的問題。


function Hook(){

  return function (initialState){

    this.state = initialState;

    return [

      this.state,

      function(newState){

        this.state = newState;

      }

    ];

  }

}

const useState = new Hook();

現在,解構 ituseState()的一個實例Hook()


const [state, setState] = useState(0);

console.log(state); // 0

setState({x:20});

console.log(state); // { x: 20 }

setState({x:30});

console.log(state); // { x: 30 }


查看完整回答
反對 回復 2023-07-20
  • 5 回答
  • 0 關注
  • 222 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號