【问题标题】:React material-table with lookup from remote async使用远程异步查找来反应材料表
【发布时间】:2019-09-23 17:23:12
【问题描述】:

我需要设置从远程数据中查找材料表列。 我试过了,还是不行:

const [authors, setAuthors] = useState([]);
const [state, setState] = React.useState({
    columns: [
        {field: 'id', title: 'ID', editable: 'never'},
        {field: 'title', title: 'Titolo'},
        {
            field: 'author_id',
            title: 'Autore',
            // lookup: {12: 'cesare pavese', 124: 'david mccomb', 3: 'stephen king'},
            lookup: {authors},
        }
    ]
});

useEffect(() => {   
    async function getAuthors() {
        const result = await axios.get(AUTHORS_ALL);
        setAuthors(result.data);
    }

    getAuthors();
}, []);

远程调用有效,但不设置查找。 不知道有没有可能?

【问题讨论】:

  • 你能告诉我们你的数据吗?不仅仅是查找,还有你传递给数据道具的内容?或者你渲染的代码?因为您的 useEffect 是正确的,但可能是您将数据传递到材料表的方式。

标签: reactjs use-effect material-table


【解决方案1】:

在这种情况下,结果是一个承诺,因此您必须使用 .then() 来分配它,如下所示:

useEffect(() => {   
async function getAuthors() {
    const result = await axios.get(AUTHORS_ALL);        
    setAuthors(result.data);  
}
getAuthors();
}, []);

希望对你有帮助。

【讨论】:

  • 嗨!非常感谢,但我收到错误“未处理的拒绝(TypeError):result.then 不是函数”......你知道为什么吗?
  • 添加 .catch() 函数来获取错误,可能你的获取请求返回错误。
  • 不,你不能等待。等待或使用 then。
【解决方案2】:

我是这样做的:

useEffect(() => {

    async function getAuthors() {
        const result = await axios.get(AUTHORS_ALL);
        return result;
    }

    getAuthors().then(res => {
        console.log(res.data);
        setAuthors(res.data);
    });
}, []);

数据到达正确,但无论如何查找未填充!

【讨论】:

    【解决方案3】:

    我认为您只需要为其分配一个数组,而不是:

    {12: 'cesare pavese', 124: 'david mccomb', 3: 'stephen king'}
    

    这样做:

    ['cesare pavese', 'david mccomb', 'stephen king']
    

    通过做得到它们:

    setAuthors(Object.values(res.data))
    

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 2020-09-04
      • 2020-12-12
      • 2020-10-08
      • 2022-01-22
      • 2019-05-14
      • 2020-10-14
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多