Context API应用探索
P粉964682904
P粉964682904 2023-09-09 15:34:11
0
1
590

我尝试过多种方法。看了上面很多解决方案,还是没能解决这个问题。任何人都可以帮助我在我的项目中使用上下文吗?

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粉964682904
P粉964682904

全部回复(1)
P粉764003519

我认为您的问题是 NumberOfContestParticipated 组件不是 Provider 组件的子组件,因此当状态更改时上下文仍然未定义。另外,我觉得很奇怪,您将应用程序包装在提供程序中两次,如果您包装整个 App 组件,则不需要这样做。

查看这篇文章,了解有关如何操作的更多信息使用上下文。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板