搜尋

首頁  >  問答  >  主體

Context API應用探索

我嘗試過多種方法。看了上面很多解決方案,還是沒能解決這個問題。任何人都可以幫助我在我的專案中使用上下文嗎?

SearchContext.jsx

import { createContext } from 'react';

const SearchContext = createContext();

export default SearchContext;

Search.jsx

##
import * as React from 'react';
import { useState, useContext } from 'react';
import Paper from '@mui/material/Paper';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import SearchIcon from '@mui/icons-material/Search';
import { Box, IconButton, InputBase } from '@mui/material';
import SearchContext from '../Context/SearchContext';

export default function Search() {
    const [searchQuery, setSearchQuery] = useState('');
    const handleSubmit = (event) => {
        event.preventDefault();
    };

    const handleInputChange = (event) => {
        setSearchQuery(event.target.value);
    };
    return (
        <SearchContext.Provider value={searchQuery} >
            <Box display='flex' alignItems='center' justifyContent='center' paddingTop='20px'>
                <Paper component="form" sx={{ p: '2px 10px', display: 'flex', width: '50%' }} onSubmit={handleSubmit}>
                    <IconButton type="button" sx={{ p: '10px' }} aria-label="search">
                        <AccountCircleIcon fontSize='large' />
                    </IconButton>
                    <InputBase
                        sx={{ ml: 1, flex: 1 }}
                        placeholder="Search User"
                        inputProps={{ 'aria-label': 'search user' }}
                        onChange={handleInputChange}
                    />
                    <IconButton type="submit" sx={{ p: '10px' }} aria-label="search">
                        <SearchIcon fontSize='large' />
                    </IconButton>
                </Paper>
            </Box>
        </SearchContext.Provider>
    );
}

我就是這麼用的。這是對的嗎 ? 我後來在這裡用過它

import React, { useContext, useEffect, useState } from 'react';
import { ApiService } from '../../API/ApiService';
import SearchContext from '../../Context/SearchContext';


function NumberOfContestParticipated({ handle }) {
    const [contestCount, setContestCount] = useState(null);
    const searchQuery = useContext(SearchContext);
    console.log(searchQuery);
    useEffect(() => {
        const fetchData = async () => {
            const ratingUrl = `https://codeforces.com/api/user.rating?handle=${handle}`;
            const ratingData = await ApiService(ratingUrl);

            if (ratingData && ratingData.status === 'OK') {
                setContestCount(ratingData.result.length);
            } else {
                setContestCount(0);
            }
        };

        fetchData();
    }, [handle]);

    return (
        <div>
            {contestCount !== null ? (
                <p>Number of contests participated by {handle}: {contestCount}</p>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
}

export default NumberOfContestParticipated;

但是當我控制台記錄 searchQuery 時,它給出了未定義的值。我做錯了什麼?

Index.js

#
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import SearchContext from './Context/SearchContext';

ReactDOM.render(
  <SearchContext.Provider>
    <App />
  </SearchContext.Provider>
  , document.getElementById('root')
);

P粉964682904P粉964682904444 天前582

全部回覆(1)我來回復

  • P粉764003519

    P粉7640035192023-09-10 15:11:02

    我認為您的問題是 NumberOfContestParticipated 元件不是 Provider 元件的子元件,因此當狀態變更時上下文仍然未定義。另外,我覺得很奇怪,您將應用程式包裝在提供者中兩次,如果您包裝整個 App 元件,則不需要這樣做。

    查看這篇文章,以了解有關如何操作的更多資訊使用上下文。

    回覆
    0
  • 取消回覆