如何过滤使用ReactJS渲染的道具?

时间:2018-05-01 22:06:47

标签: javascript reactjs

我有一个代码可以获取json-server的数据。并在屏幕上呈现七个名字。我希望按输入过滤并仅渲染已过滤的元素。

我的Apps.js:

class AppRouter extends React.Component {
  state = {
employeeCurrent: [],
employee: []
  };

  componentDidMount() {
axios
  .get("http://127.0.0.1:3004/employee")

then(response => this.setState({ employee: response.data }));
  }

  add = name => {
this.setState(prevState => {
  const copy = prevState.employeeCurrent.slice();
  copy.push(name);
  return {
    employeeCurrent: copy
  };
});
  };

  render() {
return (
  <Router>
    <div className="router">
      <Route
        exact
        path="/"
        render={props => (
          <Home
            {...props}
            add={this.add}
            employee={this.state.employee}
            currentEmployee={this.state.currentEmployee}
          />
        )}
      />
      <Route
        path="/user/:id"
        component={props => (
          <User
            {...props}
            employee={this.state.employee}
            currentEmployee={this.state.currentEmployee}
          />
        )}
      />
    </div>
  </Router>
);
  }
}

我的body.js(具有渲染功能的地方)

 class Body extends React.Component {
  getName = () => {
    const { employee, add } = this.props;
    return employee.map(name => (
      <Link className="link" to={`/user/${name.name}`}>
        {" "}
        <div onClick={() => add(name)} key={name.id} className="item">
          {" "}
          <img
            className="img"
            src={`https://picsum.photos/${name.name}`}
          />{" "}
          <h1 className="name"> {name.name} </h1>
        </div>{" "}
      </Link>
    ));
      };

      render() {
    return <div className="body">{this.getName()}</div>;
      }
    }

我试图将状态传递给App。 JS却没有成功。我在身体里尝试了一切。 JS但也没有成功。有人可以帮我怎么做吗?

  

我打电话,所以有些东西不好缩进。遗憾!

1 个答案:

答案 0 :(得分:1)

试试这个,

class Body extends React.Component {
  getName = () => {
    const { employee, add } = this.props;

    //Filter  names in employee array with input 

    const filterNames = employee.filter(x => x.name === "check with the input value" );

     // Then map over the filtered names

    return filterNames.map(name => (
      <Link className="link" to={`/user/${name.name}`}>
        {" "}
        <div onClick={() => add(name)} key={name.id} className="item">
          {" "}
          <img
            className="img"
            src={`https://picsum.photos/${name.name}`}
          />{" "}
          <h1 className="name"> {name.name} </h1>
        </div>{" "}
      </Link>
    ));
      };

      render() {
    return <div className="body">{this.getName()}</div>;
      }
    }