我正在开发一个ReactJs应用程序,现在我需要将从Main.js页面点击的ID传递给Sofa.js,根据刚刚点击的ID显示不同的信息。 我已经将我的代码格式化为PHP,我希望ReactJs有一个全局变量,就像$_GET一样。也许它存在,只是我不知道。我一直在搜索,但没有找到我要的东西。下面是代码。
未包含任何导入的Main.js代码:
export class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
models: [],
offset: offset,
limit: limit
};
}
componentDidMount() {
/* Some code not relevant to the question, for getting API token */
fetch('url/couch-model?offset=' + offset + '&limit=' + limit, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
models: json.results,
isLoaded: true
}, () => { });
})
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Loading...
</div>
)
} else {
return (
<div>
{models.map(model =>
<a href={"/sofa?id=" + model.id} key={model.id}>
<div className="Parcelas">
<img src={"url" + model.image} className="ParcImage" alt="sofa" />
<h1>{model.name}</h1>
<p className="Features">{model.brand.name}</p>
<button className="Botao">
<p className="MostraDepois">Ver Detalhes</p>
<span>+</span>
</button>
<img src="../../img/points.svg" className="Decoration" alt="points" />
</div>
</a>
)}
<PageButtons offset={offset} />
</div>
)
}
}
}
正如您所看到的,在第二个返回中,<a>
发送了一个ID,尽管我不确定这是否是正确的方式。我尝试编写类似于此路径的route-js代码:/sofa/:id
,但不知何故,/sofa/1中的CSS停止工作,无论ID是什么。
现在是Sofa.js代码,没有导入,只有相关代码:
export class Sofa extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
model: {}
};
}
componentDidMount() {
fetch(url + '/couch-model/1{/*this show be id clicked and sent by url*/}/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
model: json,
isLoaded: true
}, () => {});
})
}
render() {
const { model, isLoaded } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Estamos a preparar o seu sofá!
</div>
)
} else {
return (
<div id="Esquerda">
<h2>{model.area_set.map(area => area.name)}</h2>
<h1>{model.name}</h1>
<p>Highly durable full-grain leather which is soft and has a natural look and feel.</p>
<h3>Design</h3>
<h4>Hexagon</h4>
</div>
);
}
}
}
此外,这是route.js文件:
const Routes = (props) => (
<BrowserRouter>
<Switch>
<Route path='/sofa/:id' component={Sofa}/>
<Route path='/home' component={Home}/>
<Route path='*' component={NotFound}/>
</Switch>
</BrowserRouter>
);
export default Routes;