gpt4 book ai didi

javascript - 从 React Context 返回 Cannot read property 'map' of undefined

转载 作者:行者123 更新时间:2023-12-04 17:28:01 26 4
gpt4 key购买 nike

我正在尝试使用 Context 在 React 中的两个组件之间传递数据。我要传递的数据是数组 searchResults。我已经设置了上下文和所有内容,但是当我尝试在我的第二个组件中使用数组时,我得到已通过上下文发送?

这是我的第一个组件:

import React, { Component } from "react";
import axios from "axios";
export const SearchContext = React.createContext();

class Search extends Component {
state = {
searchResults: [],
isSearched: false
}


getSearchQuery = (event) => {
const queryString = document.querySelector(
".search-input"
).value;

if (event.keyCode === 13) {
axios.post("http://localhost:3001/search", {
queryString: queryString,


}).then(response => {

this.setState({ ...this.state, searchResults: response.data });

});
this.setState({ ...this.state, isSearched: true });
window.location.href = '/blog/searchResults'
}
};

render() {
console.log(this.state.searchResults)
return (
<SearchContext.Provider value={this.state.searchResults}>
<input
type="text"
className="search-input"
onKeyDown={(e) => this.getSearchQuery(e)}
/>
</SearchContext.Provider>

);
}
}

export default Search;

我的第二个组件应该使用数组:

import React, { Component } from 'react';
import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
import { SearchContext } from '../../components/Search/Search.jsx';
let title = 'Blog'

class SearchResultsPage extends Component {
render() {
return (
<div>
<CustomHeader
title={title}
/>

<SearchContext.Consumer>
{(value) => value.map(result => (
<div key={result._id}>
<div>
</div>
<article>
{value.postContent}
</article>
</div>
)
)}
</SearchContext.Consumer>
<Footer />
</div>
)
}
};

最佳答案

我觉得需要返回

<SearchContext.Consumer>
{value.map(result => {
return ( <div key={result._id}>
<div>
</div>
<article>
{value.postContent}
</article>
</div>

)}
)}
</SearchContext.Consumer>

关于javascript - 从 React Context 返回 Cannot read property 'map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62101621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com