簡體   English   中英

從外部 function 調用 React state 方法

[英]Call React state methods from external function

我正在構建一個使用一些 state 變量的 React 功能組件,我試圖從按鈕單擊事件調用的外部 function 修改其中一些變量,但是當我將對 state 方法的引用傳遞給這個外部 function 時,所有這些都是未定義的。 可能是什么原因? 如果我只是將完全相同的代碼放入功能組件中,它會按預期完美運行。

import React from "react";
import {CodeArea, Table, EmptyField, Button} from '../util/util.js'
import {Step, Load} from "./buttons.js" // The external function in question, Loadfunction 

Core(props){
    const registersInitial = new Array(32).fill(0);
    let buttonNamesInitial = ['LOAD','play', 'step-forward', 'run-to', 'step-back','pause','halt', 'rerun', 'add'];

    const [bigText, setText] = React.useState();
    const [registers, setRegisters] = React.useState(registersInitial);
    const [running, setRunning] = React.useState(false);
    const [programCounter, setProgramCounter] = React.useState(0);
    const [buttonNames, setButtonNames] = React.useState(buttonNamesInitial);
    const [lines, setLines] = React.useState([]);

    const getBigText = () => {
        return bigText;
    }
    const getRunning = () =>{
        return running;
    }
    const getButtonNames = () => {
        return buttonNames;
    }
    
    //... some code here thats irrelevant
    
    function getQuickbarContents(){
        let functions = [ //Backend will come here
            () => Load(setRunning, getRunning, setButtonNames, getButtonNames, setProgramCounter, setLines, getBigText), //Where Load gets called
            () => console.log("code running..."),
            () => console.log("stepping to next line..."),
            () => console.log("running to location..."),
            () => console.log("stepping..."),
            () => console.log("pausing..."),
            () => console.log("halting..."),
            () => console.log("running again..."),
            () => console.log("select widget to add...")
        ]
        let contents = [];
        let row = [];
        for (let i = 0; i<9; i++){
            row.push(<Button onClick ={functions[i]} className='quickbar' name={buttonNames[i]}/>);
            contents.push(row);
            row = [];
        }
        return contents
    }
    
    const divs = [];
    
    let buttons = getQuickbarContents();
    divs.push(<div key='left' className='left'><Table name='quickbar' rows='7' cols='1' fill={buttons}/> </div>);
    
    //... some more code to push more components do divs
    
    return divs;}
export default Core;`

按鈕看起來像這樣:

function Button({onClick, className, name}){
    return <button onClick={onClick} className={className} name={name}>{name}</button> 
}

並像這樣加載:

export function Load({setRunning, getRunning, setButtonNames, getButtonNames, setProgramCounter, setLines, getBigText}){
    let newButtonName;
    if (!getRunning()){ // Functions errors out with getRunning() undefined 
        herenewButtonName = "Reload";
    }
    else{ //while running if user wants to reload
        newButtonName = "LOAD";
    }

    let lines = getBigText().split(/\n/);
    setLines(lines);
    setProgramCounter(0);
    setRunning(!getRunning());
    
    const newButtonNames = getButtonNames().map((value, index) =>{
        if (index === 0){
            return (newButtonName);
        }
        return value;
    })
    
    setButtonNames(newButtonNames);
}

所以基本上在我的腦海中流程應該是: state 方法初始化 -> 創建按鈕組件 -> 等待點擊按鈕 -> 更新 state 變量但顯然,一路上出了問題。

我試過使用檢查模式調試,這表明實際上加載的所有參數在評估時都是未定義的。

請注意,如果我像這樣更改代碼,一切都會按預期工作,例如。 只需將整個 function 放在 React 組件中;

//... everything same as before
function getQuickbarContents(){
        let functions = [
            () =>{
                let newButtonName;
                if (!getRunning()){ //User clicks to start running
                    newButtonName = "Reload";
                }
                else{
                    newButtonName = "LOAD";
                }
            
                let lines = getBigText().split(/\n/);
                setLines(lines);
                setProgramCounter(0);
                setRunning(!getRunning());
            
                const newButtonNames = getButtonNames().map((value, index) =>{
                    if (index === 0){
                        return (newButtonName);
                    }
                    return value;
                })
            
                setButtonNames(newButtonNames)},
            () => console.log("code running..."),
            () => console.log("stepping to next line..."),
            () => console.log("running to location..."),
            () => Step(setRegisters, registers, setProgramCounter, programCounter, lines[programCounter]),
            () => console.log("pausing..."),
            () => console.log("halting..."),
            () => console.log("running again..."),
            () => console.log("select widget to add...")
        ]
//...everything same as before

因此,錯誤出在我將參數傳遞給 Load 的方式中,或者我正在做一些我不應該在 React 中做的事情。 無論哪種方式,我都不知道,有什么想法嗎?

正如@robin_zigmond 指出的那樣,問題在於在 Load 中定義參數的方式。 現在修好了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM