javascript - React 将 Props 传递给无状态功能组件
问题描述
AuthLinks 组件应在 Notifications 组件上的 notificationCount 中呈现来自 notificationCount 属性的值
我想从 notificationCount 获取值到 AuthLinks 组件,但是来自变量的值似乎应该在 AuthLinks 上。
const AuthLinks = props => {
return (
<div>
<NavLink to="/notifications">
Notifications
<span data-badge={props.notificationCount} />
</NavLink>
</div>
);
};
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Notifications extends Component {
constructor(props) {
super(props);
this.state = {
notifications: [],
};
}
componentWillMount() {
fetch("/notifications")
.then(response => {
return response.json();
})
.then(data => {
this.setState({ notifications: data });
});
}
render() {
let notificationCount = this.state.notifications.length;
let notifications = this.state.notifications.map(notification => {
return (
<ul>
<li>
<Link to={`/posts/${notification.post.title}`}>
<div>
{notification.post.title}
</div>
</Link>
</li>
</ul>
);
});
return (
<div className="column col-9">
{notificationCount}
{notifications}
</div>
);
}
导出默认通知;
不显示错误消息,但也没有呈现值
解决方案
您好,在您的通知组件中,您没有将任何道具传递给 Authlinks 功能组件。
如果我没记错的话,如果你想将 props 传递给 Authlinks,你的 Notifications 组件应该是这样的
import React, { Component } from "react";
import { Link } from "react-router-dom";
import Authlinks from 'your path'
class Notifications extends Component {
constructor(props) {
super(props);
this.state = {
notifications: [],
};
}
componentWillMount() {
fetch("/notifications")
.then(response => {
return response.json();
})
.then(data => {
this.setState({ notifications: data });
});
}
render() {
let notificationCount = this.state.notifications.length;
let notifications = this.state.notifications.map(notification => {
return (
<ul>
<li>
<Link to={`/posts/${notification.post.title}`}>
<div>
{notification.post.title}
</div>
</Link>
</li>
</ul>
);
});
return (
<div className="column col-9">
{notificationCount}
{notifications}
<Authlinks notificationCount={notificationCount}/>
</div>
);
}
推荐阅读
- c# - ListView 中列的总和
- loopbackjs - 根据 Loopback 4 中 API 的后端实现验证 openapi 3.0 API 描述
- data-distribution-service - DCPSInfoRepo 被杀
- angular - 如何在 Ionic 3 中将文件上传到设备中用户的谷歌驱动器存储
- android - 尝试添加错误的卡时,Stripe 崩溃
- python - Pandas:根据相邻行值的条件选择行
- javascript - _.findIndex() 总是返回 -1 (lodash.js)
- sockets - 单台机器可能的最大 Socket(用于 HTTP 流量)连接数
- .htaccess - .htacess 中的所有规则集中在一处
- sql - Postgres JSONB 查询简化