我有一个小联系人应用程序,显示联系人列表。我希望能够在联系人页面点击联系人时呈现路线。我没有问题渲染完整的联系人列表我只能得到一个联系人来呈现 我的联系人组件看起来像这样
class Contacts extends React.Component {
constructor() {
super();
this.state = {
contactslist: []
}
}
componentWillMount(){
let contactslistRef = firebase.database().ref('contactslist');
let _this = this;
contactslistRef.on('value', (snapshot) => {
let contactslist = snapshot.val();
let newState = [];
for (let contact in contactslist) {
newState.push({
id: contact,
name: contactslist[contact].name,
phone: contactslist[contact].phone
});
}
console.log(snapshot.val());
_this.setState({
contactslist: newState
});
})
}
render() {
return (
<div className='app'>
<h1>Contacts list</h1>
<ul>
{this.state.contactslist.map((contact) => {
return (
<li key={contact.id}>
<Link to={`/contact/${contact.id}`}>{contact.name} {contact.phone}</Link>
</li>
)
})}</ul>
</div>
);
}
}
export default Contacts;
我的联系人组件就像这样
const Contact = (props) => {
const contact = (props.match.params.id)
return (
<div className="card">
<h1>{props.name}</h1>
<h2>Phone:{props.phone}</h2>
<Link to='/contacts'>Back</Link>
</div>
)
}
export default Contact;
我有一个包含所有路线的主要组件
const Main = () => (
<main>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/contacts' component={Contacts} />
<Route path='contacts/:id' component={Contact} />
</Switch>
</main>
)
export default Main
答案 0 :(得分:0)
您可以从网址获取参数,并从firebase接收有关您的联系人的详细信息。
class Contact extends React.Component{
state = {
detail: {}
}
componentDidMount(){
const {id} = this.props.match.params;
const _this = this;
if (!id) return;
const detail = firebase.database().ref('contactslist/' + id);
detail.on('value', function(snapshot) {
_this.setState({
detail: snapshot.val()
});
});
}
}