首页 > 解决方案 > 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>
    );
  }

导出默认通知;

不显示错误消息,但也没有呈现值

标签: javascriptreactjs

解决方案


您好,在您的通知组件中,您没有将任何道具传递给 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>
    );
  }

推荐阅读