在redux-react应用程序中,我将包括我的有状态表示组件?在组件或容器文件夹中?

时间:2018-04-30 13:50:13

标签: reactjs redux react-redux

搜索组件:

import React from "react";
import SearchResults from "../SearchResults";
import PropTypes from "prop-types";

class Search extends React.Component {
  state = {
    value: ""
  };

  handleChange = event => {
    let value = event.target.value;
    this.setState({ value });
    this.props.performSearch(value);
  };

  handleSubmit = event => {
    event.preventDefault();
  };

  render() {
    return (
      <div>
        <h1>The Guardian Search App</h1>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            value={this.state.value}
            onChange={this.handleChange}
          />
        </form>
        <div>
          <SearchResults articles={this.props.articles} />
        </div>
      </div>
    );
  }
}

Search.propTypes = {
  performSearch: PropTypes.func,
  articles: PropTypes.array
};

export default Search;

搜索容器:

import React from "react";
import Search from "../../components/Search";
import { API_KEY } from "../../../config";

import fetchArticles from "../../api";

class SearchContainer extends React.Component {
  state = {
    articles: []
  };

  performSearch = event => {
    return fetchArticles(event).then(data =>
      this.setState({ articles: data.response.results })
    );
  };

  render() {
    return (
      <Search
        performSearch={this.performSearch}
        articles={this.state.articles}
      />
    );
  }
}

export default SearchContainer;

我目前正试图了解redux,以便将其转换为react-redux版本。我有一个搜索容器,我正在做mapStateToProps,很快就会编写mapDispatchToProps。但是,如果我的搜索组件还包含状态,那么我是否可以执行另一个搜索容器,然后将其状态映射到道具?

1 个答案:

答案 0 :(得分:1)

Search组件中所需的状态与您作为孩子呈现的input元素直接相关并且是必需的。因此,value组件中的Search状态应保留在组件内,而不与​​Redux关联。

没有“正确”的做法,主要是偏好和设计模式。由于您在Search组件中有一个您不希望与Redux关联的状态,我会将SearchContainer组件挂钩到您的Redux存储中以提供可以传递的文章对象数组以基础Search组件作为支柱,让该组件完全不知道Redux甚至存在。