免责声明:“ React.JS”不是我的新手。
我正在尝试从一个组件中获取值,因此可以在其他组件中使用它来显示适当的内容。组件1列出了我数据库中的所有节目。组件2在自己的页面上具有有关每个特定节目的信息。我想在不进行硬编码的情况下执行此操作,因为这可能不是一个好方法。
代码如下:
Component1.JSX
import React, { Component } from 'react';
import './SecondPage.css';
import { Button, ButtonGroup, DropdownItem, DropdownMenu, DropdownToggle, ButtonDropdown } from 'reactstrap';
import Helmet from 'react-helmet';
import axios from 'axios';
import { Link } from 'react-router-dom';
import Showing from '../Showing/Showing.jsx';
class SecondPage extends React.Component {
constructor(props) {
super(props);
this.state = {
showingsList: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
const self = this;
axios.get('/api/loadShowings')
.then(response => {
var showingsList = response.data
this.setState({ showingsList });
}
);
}
handleSubmit(){
}
render(){
return(
<div class="grid-container1">
{
this.state.showingsList.map((showing) => {
return <div showing = {showing} key = {showing.id}>
<div class="grid-item1 "><img width = "200px" height = "200px" src={showing.image}/>
<h3>{showing.title}</h3>
<h5>{showing.description}</h5>
<Link to = "/Showing">
<Button className="btnShowings">MORE</Button>
</Link>
</div>
</div>})
}
</div>
)
}
}
export default SecondPage;
Component2.JSX
import React, {Component} from 'react';
import './Showing.css';
import Helmet from 'react-helmet';
import {Button} from 'reactstrap';
import {Link} from 'react-router-dom';
import axios from 'axios';
class Showing extends React.Component{
constructor(props) {
super(props);
this.state = {
showingsList: [],
};
}
componentDidMount(){
const self = this;
axios.get('/api/loadShowings')
.then(response => {
var showingsList = response.data
this.setState({ showingsList });
console.log(showingsList["0"].title)
}
);
}
render(){
return(
<div>
{
this.state.showingsList.map((showing) => {
return <div showing = {showing} key = {showing.id}>
<Helmet>
<style>{'body { background-color: gray; }'}</style>
</Helmet>
<div class="grid-container">
<div class="item1">{showing.title}</div>
<div class="item2"><img width = "200px" height = "200px" src={showing.image}/></div>
<div class="item3">{showing.description}</div>
<div class="item4"> <a href = "/Booking">
<Button bsStyle="info" size = "lg">Make a booking</Button>
</a></div>
</div>
</div>})
}
</div>
)
}
}
export default Showing;
我尝试了从各种教程中看到的几件事-使用“ this.props.state”,但是无法正常工作,因为该示例是在主要JSX文件(App.js)上制作的。我也尝试过做axios post and get,但是它变得如此复杂。我需要使用什么的建议,因此不必为每种情况创建很多不同的页面。非常感谢你!