简体   繁体   English

为什么 onclick 函数没有呈现(React.js)?

[英]Why onclick function isn't rendering (React.js)?

I'm working on building an e-commerce website in React.我正在用 React 构建一个电子商务网站。 In which, there will be a navigation bar with all the categories and once a user clicked on a specific category, it will render all the products that belongs to the checked category in the same page.其中,将有一个包含所有类别的导航栏,一旦用户单击特定类别,它将在同一页面中呈现属于选中类别的所有产品。 In the project I have two .js files which are NavBar.js where it contains all the stuff for the navigation bar and AllItems.js where all products are rendered.在项目中,我有两个.js文件,它们是NavBar.js ,其中包含导航栏的所有内容,以及AllItems.js所有产品的AllItems.js

My problem now, is that onclick in NavBar.js doesn't render AllItems.js .我现在的问题是NavBar.js中的onclick不呈现AllItems.js It works with console.log("sss") but it doesn't work with <AllItems/>它适用于console.log("sss")但它不适用于<AllItems/>

Here is my code in NavBar.js这是我在NavBar.js代码

function NavBar() {


    const [allCategories, setAllCategories] = useState([])
    const [currency, setCurrency] = useState([])
    

    useEffect(() => {

        fetchAnyQuery(
            `
            query{
                categories{
                name
                }
            }
        `).then(data => {
            setAllCategories( data.data.categories )
        })
    },[])

    // for currency options
    useEffect(() => {

        fetchAnyQuery(`
            query{
              currencies
            }
        `
        ).then(data => {
            setCurrency(data.data.currencies)
        })
    },[])


    return (
        <nav id = "NavBar">
            <div id="NavBar-content">

                <div className = "leftSide" id = "leftNav">

                    {allCategories.map((allCategories, index) => {

                        if (index == 0){
                            // return a checked tab

                            return(
                                <>
                                    <input className='radio-category' id={allCategories.name} type='radio' name="nav" onClick={
                                        function (){
                                            console.log("ssss");
                                            <AllItems/>

                                        }

                                    } checked/>
                                    <label htmlFor={allCategories.name} className='category-label'><h5 className="tab-text">{allCategories.name.toUpperCase()}</h5></label>
                                </>
                            )

                        }
                        else {
                            // return unchecked tab

                            return(
                                <>
                                    <input className='radio-category' id={allCategories.name} type='radio' name="nav" onClick={ function (){changeCategoryState(allCategories.name); <AllItems/>} } />
                                    <label htmlFor={allCategories.name} className='category-label'><h5 className="tab-text">{allCategories.name.toUpperCase()}</h5></label>
                                </>
                            )
                        }

                    })}
                </div>

                <div className = "centerSide">
                    {/*<a href="/">*/}
                    {/*    /!*<img src={logo} />*!/*/}
                    {/*    Logo*/}
                    {/*</a>*/}

                    <button onClick={function (){ console.log(getCategoryState()) }}>
                        Abo Kalb
                    </button>
                </div>

                <div className = "rightSide">

                    <select className="currencySelector" id="currencySelector">

                        {currency.map((currency, index) =>{

                            return(
                                <option value={ JSON.stringify(currency.indexOf(index)) }  >   {getSymbolFromCurrency(currency.toString()) + " " + currency.toString()} </option>

                            )
                        })}
                    </select>
                </div>
            </div>
        </nav>
    );
}

export default NavBar;

Also, here is my code for AllItems.js file:另外,这是我的AllItems.js文件代码:

function AllItems() {

    // The state that I want to use in NavBar.js
    // const [category, setCategory] = useState([getCategoryState()])
    const [products, setProducts] = useState([])



    useEffect(() => {

        fetchAnyQuery(
            `
                query{
                    categories{
                        name
                        products{
                            name
                            id
                        }
                    }
                }
        `
        ).then(data => {

            // Here I'm trying to do all  the required stuff

           // console.log(category)

        })


    },[])


    console.log("All Items RENDERED!!")

    return (
        <>

            <h1>{ getCategoryState() }</h1>

            <div className="itemContainer" id="itemContainer">

            </div>

        </>

    )
}

export default AllItems;

From what I understood, you want to render different categories' data based on which category is clicked, but you can not call a component on the click, that's not how React works.据我了解,您希望根据点击的类别呈现不同类别的数据,但您无法在点击时调用组件,这不是 React 的工作方式。 Instead set a state and render the component conditionally according to the state value, and set the state when the component needs to be rendered.而是设置一个状态并根据状态值有条件地渲染组件,并在组件需要渲染时设置状态。

Assuming that you're fetching your items from a server, you will have to store that data in a state假设您从服务器获取您的项目,您将不得不将该数据存储在一个状态

const [allItems, setAllTems] = useState([])

Then add a state that will help you render your items conditionally然后添加一个状态来帮助您有条件地呈现您的项目

const [showAllItems, setShowAllItems] = useState(false)

In your JSX, use && to render your data when the state gets all the data在您的 JSX 中,当状态获取所有数据时,使用 && 来呈现您的数据

<> {showAllItems && <AllItems>} </>

if you're having troubles understanding how this works, I suggest you checking React documentations , it explains very well how you can manipulate the state如果您在理解它的工作原理时遇到困难,我建议您查看React 文档,它很好地解释了如何操作状态

Use a parent component to manage the state.使用父组件来管理状态。 When you update the radio input in Nav update the state, and then filter the data based on that selection.当您更新Nav的无线电输入时,更新状态,然后根据该选择过滤数据。

 const { useState } = React; function Example({ data }) { const [ items, setItems ] = useState(data); const [ selection, setSelection ] = useState(''); // When you click a button, set the selection state function handleClick(e) { setSelection(e.target.dataset.type); } // `filter` out the items you want to display // based on the selection function filteredItems() { return items.filter(item => item.type === selection); } return ( <div> <Nav> Dairy: <input onClick={handleClick} type="radio" data-type="dairy" name="food" /> Meat: <input onClick={handleClick} type="radio" data-type="meat" name="food" /> Vegetable: <input onClick={handleClick} type="radio" data-type="vegetable" name="food" /> </Nav> <Items items={filteredItems()} /> </div> ); }; // `map` over the filtered data function Items({ items }) { return items.map(item => <div>{item.name}</div>); } function Nav({ children }) { return children; } const data = [ { name: 'cow', type: 'meat' }, { name: 'bree', type: 'dairy' }, { name: 'chicken', type: 'meat' }, { name: 'sprout', type: 'vegetable' } ]; ReactDOM.render( <Example data={data} />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM