“来自父数组的React组件不是一个真正的数组”

huangapple go评论70阅读模式
英文:

react component from parent array is not an actual array

问题

I'm providing the requested translation without the code parts:

我正在尝试从 axios 的 GET 请求中传递一个数组,我的后端服务器是用 C# 编写的。
这是请求:

// GET: api/<SettingsController>
[HttpGet]
public IActionResult Get()
{
    try
    {
        return Ok(_repo.GetAccounts().ToList());
    }
    catch (Exception)
    {
        return BadRequest();
    }
}

这是我的父组件:

const SettingsPage = () => {
    const [allAccounts, setAllAccounts] = useState("");
    useEffect(() => {
        axios.get("https://localhost:9000/api/settings").then((response) => {
            setAllAccounts(response.data);
        });
    }, []);
    return (
        <Table type="הגדרות" allAccounts={allAccounts} selectAccount={selectAccount} />
    );
}

export default SettingsPage

这是我的子组件(也是另一个组件的父组件):

const Table = (props) => {
    const [allAccounts, setAllAccounts] = useState([]);
    useEffect(() => {
        setAllAccounts(props.allAccounts);
    }, []);
    return (
        {allAccounts.map((account) => {
            <TableRow account={account} />
        })}
    )
}

export default Table

然后我遇到了运行时错误:
props.allAccounts.map 不是一个函数 类型错误: props.allAccounts.map 不是一个函数

我尝试使用不同的变量(例如 var arr = [])并逐个推送每个元素,但类型错误仍然是 "props.allAccounts.ForEach 不是一个函数"。
我还尝试使用 useState 钩子中的 allAccounts 常量,结果是相同的错误。
也许值得注意的是,console.log 函数中的数组看起来不错:

(2) [{}, {}]
0: 
{id: 3, name: null, dateCreated: '2023-06-14T13:52:18.2417005', supervisorId: 1, supervisor: null, }
1: 
{id: 4, name: 'Wise-code', dateCreated: '2023-06-14T14:05:23.9261187', supervisorId: 2, supervisor: null, }
length: 2

这也是我在 Postman 中从响应中获取的数组。

英文:

I'm trying to pass an array from axios get request, my backend server is written in C#.
This is the request:

// GET: api/&lt;SettingsController&gt;
        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                return Ok(_repo.GetAccounts().ToList());
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

This is my parent component:

const SettingsPage = () =&gt; {
    const [allAccounts, setAllAccounts] = useState(&quot;&quot;);
    useEffect(() =&gt; {
        axios.get(&quot;https://localhost:9000/api/settings&quot;).then((response) =&gt; {
          setAllAccounts(response.data);
        });
      }, []);
    return (
                &lt;Table type=&quot;הגדרות&quot;  allAccounts = {allAccounts} selectAccount = {selectAccount}/&gt;
    )
}

export default SettingsPage

That is my child component (which is also a parent to a different component):

const Table = (props) =&gt; {
    const [allAccounts, setAllAccounts] = useState([]);
    useEffect(()=&gt;{
        setAllAccounts(props.allAccounts);
    },[])
    return (
                    {allAccounts.map((account) =&gt;{
                        &lt;TableRow account = {account} /&gt;
                    })}
    )
}

export default Table

And I bump into a runtime error:
props.allAccounts.map is not a function
TypeError: props.allAccounts.map is not a function

Iv'e tried to use a different variable (var arr = []) and push each element seperatly, the type error is just "props.allAccounts.ForEach is not a function".
Iv'e also tried to use the allAccounts constant from the useState hook and the result is the same error.
It might be important also to acknowledge that the array in the console.log function is looking okey:

(2) [{…}, {…}]
0
: 
{id: 3, name: null, dateCreated: &#39;2023-06-14T13:52:18.2417005&#39;, supervisorId: 1, supervisor: null, …}
1
: 
{id: 4, name: &#39;Wise-code&#39;, dateCreated: &#39;2023-06-14T14:05:23.9261187&#39;, supervisorId: 2, supervisor: null, …}
length
: 
2
[[Prototype]]
: 
Array(0)

This is also the array i get from the response in postman.

答案1

得分: 0

你已经将SettingsPage组件中的allAccounts作为props传递给Table组件。因此,在Table组件中,您可以直接访问它,无需使用useEffect。

    return (
        {
            allAccounts.map((account) =&gt;  &lt;TableRow account={account} key={account.id} /&gt;)
        }
    )
}

export default Table;

另外,最好在SettingsPage中将状态初始化为空数组,以便在第一次渲染时不会出现问题。

const [allAccounts, setAllAccounts] = useState([]);

英文:

You are already passing allAccounts from SettingsPage component to the Table component as props. So you can access it in the Table component directly, without using useEffect.

const Table = ({allAccounts}) =&gt; {    
    return (
        {
            allAccounts.map((account) =&gt;  &lt;TableRow account={account} key={account.id} /&gt;)
        }
    )
}

export default Table;

Also you had better to initialize the state to empty array in SettingsPage so that it does'nt cause problem in the first render.

const [allAccounts, setAllAccounts] = useState([]);

huangapple
  • 本文由 发表于 2023年6月15日 15:46:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定