如何使用钩子useState获取当前状态?

时间:2020-10-23 11:55:16

标签: reactjs

具有两个组成部分:

const MassViewer:React.FC = (props) => {

    const [checkInput, setCheckInput] = useState<string>('Fill the field');

    function AddBrand (name: string) {
        let array: string[] = opNames.slice();

            function checkAvailability(array: string[], name: string) {
                return array.some(function(arrVal) {
                    return name === arrVal;
                });
            }
            if (checkAvailability(array, name) === false) {
                setOpNames([...opNames, name]);
                setCheckInput('Added');
    
            } else {
                setCheckInput('Already yet');
            }
    
            function Message(value: string){
                setCheckInput(value);
            }
    }

    ....

    return (
        <div className="allContainers">
            <div className="opNames">
                <ElementList opNames={opNames} />
            </div>
            <div>
                <AddOperator AddBrand={AddBrand} message={checkInput}/>
            </div>
            <div>
                <DelOperator DeleteBrand={DeleteBrand} brand={opNames} />
            </div>
        </div>
);
}

export const AddOperator:React.FC <AddOperatorProps> = (props) => {

    const [message2, setMessage2] = useState<string>(props.message);

    function handleAddOp (e: React.MouseEvent<HTMLElement, MouseEvent>) {
        e.preventDefault();
        const inputResult: string = inputOp.slice();

        if (inputResult.length >= 1) {
            props.AddBrand(inputResult);
            setInputOp('');
            setMessage2(props.message);
        } else {
            setMessage2('Didnt fill this field');
            setInputOp('')
        }
    }

    return (
  
  <div>{message2}</div>
        ....
    )
}

在AddOperator组件中调用handleAddOp函数时,inputResult发送到MassViewer组件中的AddBrand函数。满足条件后,状态将记录在AddOperator组件中,但状态为1渲染滞后。据我了解,我需要使用useEffect挂钩,但是我不了解文档中的操作方法,请告诉我如何实现它。

0 个答案:

没有答案