【发布时间】:2019-01-11 02:10:05
【问题描述】:
我正在用 ReactJs 开发一个应用程序,现在我需要将点击的 ID 从 Main.js 页面传递到 Sofa.js,这将根据不同的情况显示不同的信息您刚刚单击的 ID。
我将我的 ming 全部格式化为 PHP,我希望 ReactJs 有一个像 $_GET ahah 这样的全局变量。也许是这样,我只是现在不知道。我一直在寻找,但没有找到我想要的东西。我将在下面显示代码。
不包含导入的 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;
【问题讨论】:
标签: javascript reactjs get fetch-api