我已经创建了一个React应用程序,它基本上有3条路线:
我需要什么
在根/条目和Instagram上,我想创建一个非常类似于Instagram的体验:https://www.instagram.com/p/BjXyK9WAEjH/?taken-by=amazon
我希望用户点击任何产品来触发到root/items/:itemId的路由更改,并有一个模态窗口显示(以显示更多有关产品的信息),而没有产品列表是RE呈现的。
当前发生的事情:
有谁有主意吗?非常感谢。
发布于 2018-09-09 15:08:41
你可以:
1.使用这2条路由呈现相同的组件
root/items和root/items/:itemId都呈现相同的ProductList组件,如果路由中的id存在,您应该签入呈现函数,并有条件地呈现带有信息的模式。您必须在componentDidMount()或shouldComponentUpdate()中检查服务器中的信息,看看如何在官方文档中实现这些信息。
或
2.不要使用路由,另一个组件的条件呈现
您可以有一个自定义组件(ProductInfo),它接收产品的id作为支持,并呈现产品的信息。在componentDidMount()函数中,您可以查询服务器以获取并显示信息。现在,在产品列表组件(ProductList)中,您可以使用在道具中传递的id对ProductInfo进行有条件的呈现。
ProductInfo
// your imports here
class ProductInfo as Component {
constructor(){
this.state = {info:{}}
}
componentDidMount(){
// load info and set info in state using this.props.id
}
render(){
// check if info is set and render all the info however you like
return(){
<div>{JSON.stringify( this.state.info )}</div>
}
}
}ProductList
//imports here
//import a Modal, or implement however you like, with bootstrap for example
import ProductInfo from './ProductInfo';
class ProductList as Component {
constructor(){
this.state = {infoId: -1}
}
changeId(e){
// get the id from the pressed button (or link or whatever component you are using)
// set the id in the state, remember to clean the state after the modal has been closed: set it back to -1.
}
render(){
// check if id is set
let {infoId} = this.state;
let renderModal = infoId > -1;
return(){
<div>
{renderModal &&
<Modal>
<ProductInfo id={infoId}/>
</Modal>
}
<ul>
<li>
<button
type={'button'}
name={'id1'}
onChange={(e) => this.changeId(e)}>
Info 1
</button>
</li>
<li>
<button
type={'button'}
name={'id2'}
onChange={(e) => this.changeId(e)}>
Info 2
</button>
</li>
<li>
<button
type={'button'}
name={'id3'}
onChange={(e) => this.changeId(e)}>
Info 3
</button>
</li>
</ul>
</div>
}
}
}这是一个简单的例子,有很多方法可以用更好的方式来做,但我认为这回答了你的问题。
防止组件的重新呈现。
如果您仍然有重新呈现后,这些建议,您可能是呈现每次信息是加载。为了防止这种情况,将信息保持在状态,并且只在加载信息时执行条件呈现。
import api from './api'; // your custom api component to get data
class ProductList as Component {
constructor(){
this.state = {list:[], dataLoaded: false, infoId:-1}
}
...
componentDidMount(){
let myList = api.getList(); // basically call any function that gets your data
this.setState({
list:myList , dataLoaded: true
});
}
changeId(e){
// same as previous example
}
render(){
// only render list if data is loaded using conditional rendering
//
let {dataLoaded, list, infoId} = this.state;
let renderModal = infoId> -1;
return(
<div>
{renderModal &&
<Modal>
<ProductInfo id={infoId}/>
</Modal>
}
{dataLoaded &&
<ul>
<li>
// render your list data here using the variable list from the state
<li>
</ul>
}
</div>
);
}
}这将防止在重新呈现列表时的反应,即使你显示模态。
https://stackoverflow.com/questions/52236036
复制相似问题