【问题标题】:How to map array from localStorage to table in reactJS?如何将数组从localStorage映射到reactJS中的表?
【发布时间】:2021-12-05 13:50:45
【问题描述】:

我正在尝试将数组数据从 localStorage 映射到我的反应表,但格式如下所示:

但我希望它的格式如下:

我现在使用的代码是这样的:

const get = JSON.stringify(localStorage.getItem('pls'));
const setUs = ([get]);
...
function handleSubmit(e){
   e.preventDefault();
   var js = localStorage.getItem('Data');
   var loc = [js];
   loc.push(document.getElementById("inputKey").value);
   localStorage.setItem("Data", loc);
}
...
return(
   <div>
     <Table>
       <tbody>
         {(setUs.map((m,i) => (
             <tr key={`${m+i}`}>
                <td>{m}</td>
             </tr>
          )))}
       <tbody>
     </Table>
   </div>
)
...

我不确定如何像第二张图片那样格式化它。我尝试过使用扩展运算符,尝试不同的方法,例如JSON.parse()JSON.stringify(),但数组变成了[[[,\\input1\]\\input2\\]\input3\\] 之类的东西。任何帮助将不胜感激。

我正在使用 reactJS 和 reactstrap。

【问题讨论】:

    标签: javascript reactjs reactstrap


    【解决方案1】:

    您可以将hooks 用于localStorage

    const useLocalStorage = (name, defaultValue) => {
    
        const [currentValue, setCurrentValue] = useState(JSON.parse(localStorage.getItem(name)) ?? defaultValue);
        const callback = useDelay(delay, currentValue);
    
        useEffect(() => {
            localStorage.setItem(name, JSON.stringify(currentValue));
        }, [currentValue]);
    
        return [currentValue, setCurrentValue];
    }
    
    export default useLocalStorage;
    

    怎么用?

    import useLocalStorage from '...';
    
    const Component = () => {
        const [pls, setPls] = useLocalStorage('pls', []);
    
        return (
            <>
                {pls.map(v => (
                    H E R E
                ))}
            </>
        );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-25
      • 2017-12-26
      • 2020-08-14
      • 2016-08-02
      • 1970-01-01
      • 2021-08-14
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多