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>
);
}
导出默认通知;
不显示任何错误消息,但也未呈现该值
答案 0 :(得分:1)
您好,在您的Notificatiions组件中,您尚未将任何道具传递给Authlinks功能组件。
如果我没记错的话,如果您想将道具传递给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>
);
}
答案 1 :(得分:0)
如果要传递道具,请将属性设置为Component
<AuthLink notificationCount={...} />
答案 2 :(得分:0)
另一种优雅的方法。
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function Counter(props) {
const {
count: [count, setCount]
} = {
count: useState(0),
...(props.state || {})
};
return (
<div>
<h3>{count}</h3>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<h2>Lifted state</h2>
<Counter state={{ count: [count, setCount] }} />
<Counter state={{ count: [count, setCount] }} />
<h2>Isolated state</h2>
<Counter />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);