javascript ReactJS如何同步我的文本输入和按钮?

k5ifujac  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(127)

我正在做一个简单的搜索栏。input标签读取一个字符串,一旦内容发生变化,状态inputString就会更新。一旦用户单击“search”按钮,我们就拆分“inputString”并将string[]分配给状态“keywords”,然后将使用这样的数组发送请求。
我对JS中异步问题的了解仍然有限,所以我想知道如何确保每次单击按钮时,我都会拆分最新的inputString?(console.log告诉我,我没有这样做,但这是另一个异步问题吗?)

import React, { useState } from "react";

export default function Search(){
    const [inputString, setInputString] = useState('');
    const [keywords, setKeywords] = useState([]);

    function sendSearchKeywords(){
        const InputStringRemovedSpace = inputString.replace(/ +(?= )/g,'');
        setKeywords(InputStringRemovedSpace.split(' '));
        console.log(inputString);
        //do something about request here
        console.log(keywords);
    }
    return (
        <div>
            <div>
                <input type='text' placeholder="enter your keywords" onChange={(e)=>{
                    setInputString(e.target.value);
                }}/>
                <button onClick={()=>{
                    sendSearchKeywords();
                }}>Search</button>
            </div>
        </div>
    );
}
qni6mghb

qni6mghb1#

响应setState is not asynchronous,但我们可以使用useEffect挂接。

import React, { useState } from "react";

export default function Search(){
    const [inputString, setInputString] = useState('');
    const [keywords, setKeywords] = useState([]);

    React.useEffect(() => {
      console.log(inputString);
      //do something about request here 
      console.log(keywords);
    }, [keywords]);

    function sendSearchKeywords(){
        const InputStringRemovedSpace = inputString.replace(/ +(?= )/g,'');
        setKeywords(InputStringRemovedSpace.split(' '));
    }

    return (
        <div>
            <div>
                <input type='text' placeholder="enter your keywords" onChange={(e)=>                                                
                {
                    setInputString(e.target.value);
                }}/>
                <button onClick={()=>{
                    sendSearchKeywords();
                }}>Search</button>
            </div>
        </div>
    );
}

相关问题