gpt4 book ai didi

javascript - 在 React 中将状态数组从一个组件传递到另一个组件

转载 作者:行者123 更新时间:2023-12-01 00:13:58 29 4
gpt4 key购买 nike

我的组件中有一个 saved[] 数组。我想将这些数据从一个组件传递到另一个组件。

我尝试过以下方法:

<Home default path='/news' savedArticles={this.state.saved}/>

但这会引发错误,因为它显示 TypeError: Cannot read property 'saved' of null

所以这是拥有数据的组件。

NewsMain.js

import React, { Component } from 'react';
import '../news-main/news-main.css';
import News from '../news/news';
import NewsHero from '../news-hero/news-hero';
import Sports from '../sports/sports';

class NewsMain extends Component {
render() {
return (
<div>
<NewsHero />
<News />
<Sports />
</div>
)
}
}
export default NewsMain;

数据来自NewsHero/>组件。

news.hero.js

import React, { Component } from 'react';
import './news-hero.css';
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";

const responsive = {
superLargeDesktop: {
breakpoint: { max: 4000, min: 3000 },
items: 1,
},
desktop: {
breakpoint: { max: 3000, min: 1024 },
items: 1,
},
tablet: {
breakpoint: { max: 1024, min: 464 },
items: 1,
},
mobile: {
breakpoint: { max: 464, min: 0 },
items: 1,
},
};

class NewsHero extends Component {
state = {
loading: false,
data: [],
headline: [],
saved: []
}

saved = headline => {
this.setState(
(prevState) => ({ saved: [...prevState.saved, headline] }),
() => {
console.log('Saved articles = ', this.state.saved);
alert('Article saved');
localStorage.setItem('saved', JSON.stringify(this.state.saved));
localStorage.getItem('saved');
});
}

constructor(props) {
super(props)
this.saved = this.saved.bind(this)
}

onError() {
this.setState({
imageUrl: "../assets/img-error.jpg"
})
}

componentDidMount() {
this.setState({ loading: true, saved: localStorage.getItem('saved') ? JSON.parse(localStorage.getItem('saved')) : [] })
fetch('https://newsapi.org/v2/everything?q=timbaland&domains=rollingstone.com,billboard.com&excludeDomains=townsquare.media&apiKey=8ee8c21b20d24b37856fc3ab1e22a1e5')
.then(headline => headline.json())
.then(headline => this.setState({ headline: headline.articles, loading: false }, () => console.log(headline.articles)))
}

render() {

return (
<div className="hero">
<h2 className="text-left">News</h2>

{this.state.loading
? "loading..."
: <div>
<Carousel
additionalTransfrom={0}
showDots={true}
arrows={true}
autoPlaySpeed={3000}
autoPlay={false}
centerMode={false}
className="carousel-hero"
containerClass="container-with-dots"
dotListClass="dots"
draggable
focusOnSelect={false}
infinite
itemClass="carousel-top"
keyBoardControl
minimumTouchDrag={80}
renderButtonGroupOutside={false}
renderDotsOutside
responsive={responsive}>
{this.state.headline.map((post, indx) => {
return (
<div className="text-left mt-5" key={indx}>
<img className="media-img card-img-top card-img-hero" src={post.urlToImage} alt="Alt text"></img>
<div className="card-body container hero-text-body">
<h1 className="card-title hero-title text-truncate">{post.title}</h1>
<button className="btn-primary btn mt-2 mb-4" onClick={() => this.saved(post)}>Add this article</button>
<p className="card-text">{post.description}</p>
<a href={post.url} target="_blank" rel="noopener noreferrer">Read More</a>
</div>
</div>
)
})}
</Carousel>
</div>
}
</div>
)
}
}
export default NewsHero;

我想将保存的数组传递给其他组件,例如

app.js

import React, { Component } from 'react';
// import logo from './logo.svg';
import './App.css';
import Header from './header/header';
import NewsMain from './news-main/news-main';
import Footer from './footer/footer';
import Home from './home/home';
import { Router } from '@reach/router';

class App extends Component {

render() {
return (
<div className="App">
<Header />
<div>
<Router>
<Home default path='/news' savedArticles={this.state.saved} />
<NewsMain path='/news' />
</Router>
</div>
<Footer title="Footer" />
</div>
)
}
}
export default App;

有什么想法吗?

最佳答案

您尚未在应用中的任何位置启动状态,因此 this.state未定义

您的 app.js 应如下所示:

import React, { Component } from 'react';
// import logo from './logo.svg';
import './App.css';
import Header from './header/header';
import NewsMain from './news-main/news-main';
import Footer from './footer/footer';
import Home from './home/home';
import { Router } from '@reach/router';

class App extends Component {
constructor(props) {
super(props);
this.state = {saved: []};
}
render() {
return (
<div className="App">
<Header />
<div>
<Router>
<Home default path='/news' savedArticles={this.state.saved} />
<NewsMain path='/news' />
</Router>
</div>
<Footer title="Footer" />
</div>
)
}
}
export default App;

看这里 https://it.reactjs.org/docs/state-and-lifecycle.html有关 ReactJS 中状态和生命周期的更多信息。

关于javascript - 在 React 中将状态数组从一个组件传递到另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59897136/

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