如何在 ReactJS 中通过传入的 prop 组件为 useReducer 提供初始状态?

时间:2021-02-17 03:47:57

标签: javascript reactjs

我正在处理一个表组件,我正在通过名为 products 的变量传递数据。如果我映射它,该组件可以显示产品,但它不会传递给初始状态变量对象。 我的目标是在 Table.body 组件中调用 data.map。 谢谢!

function exampleReducer(state, action) {
    switch (action.type) {
        case 'CHANGE_SORT':
            if (state.column === action.column) {
                return {
                    ...state,
                    data: state.data.slice().reverse(),
                    direction:
                        state.direction === 'ascending' ? 'descending' : 'ascending',
                }
            }

            return {
                column: action.column,
                data: _.sortBy(state.data, [action.column]),
                direction: 'ascending',
            }
        default:
            throw new Error()
    }
}
import React, { useReducer } from 'react'
import { Table } from 'semantic-ui-react'
import _ from 'lodash'



function TableSorter({products}) { PROBLEM STARTS HERE
    const initialState = {
        column: null,
        data: products, PROBLEM STARTS HERE
        direction: null,
    }

    const [state, dispatch] = useReducer(exampleReducer, initialState)

    const { column, data, direction } = state
        
    console.log(`products: ${products}`)
    console.log(`initial state data: ${data}`)

    return (
        <Table sortable celled fixed>
            <Table.Header>
            </Table.Header>
            <Table.Body>
                {products && products.map(({name, expiration_date, sku, category, price, shipment_batch}) => (
                    <Table.Row key={name}>
                        <Table.Cell>{name}</Table.Cell>
                        <Table.Cell>{expiration_date}</Table.Cell>
                        <Table.Cell>{sku}</Table.Cell>
                        <Table.Cell>{category}</Table.Cell>
                        <Table.Cell>{price}</Table.Cell>
                        <Table.Cell>{shipment_batch}</Table.Cell>
                    </Table.Row>
                ))}
            </Table.Body>
        </Table>
    )
}

export default TableSorter

Displayed in the console is what products is displaying vs what initial state data is displaying.

New Edit:调用TableSorter的组件 它对本地主机服务器进行 axios 调用并将数据传递给 TableSorter。我希望它以组件形式存在,以便以后可以重用,因为我可能会在另一个页面中使用它。 /* eslint-disable no-unused-vars */ 从“反应”导入反应,{useState,useEffect} 从 'axios' 导入 axios 从 "../Components/TableSorter" 导入 TableSorter;

function SearchFilter() {

    const login_url_string = "http://localhost:5000/search";

    const [productList, setProductList] = useState([])

    useEffect(() => {
        axios.get(login_url_string)
            .then(res => {
                setProductList(res.data.products)
            })
    }, [])
    return (
        <div>
            <TableSorter products={productList}/>
        </div>
    )

}

export default SearchFilter

0 个答案:

没有答案
相关问题