简体   繁体   English

结合redux状态和react状态

[英]Combine redux state with react state

What I'm trying to do here is to make a search bar with redux state. 我在这里想要做的是使搜索栏具有redux状态。 The data structure looks like this and it's from firebase. 数据结构看起来像这样,它来自firebase。

-LHNGtHa-PgB00-Y5R8q: {
    createdAt: 1531563127745
    imageLinks: [ 
        "https://cdn.pixabay.com/photo/2018/06/28/17/02/...",
        "https://cdn.pixabay.com/photo/2018/06/28/17/02/...",
        "https://cdn.pixabay.com/photo/2018/06/28/17/02/..."]
    tag: "asdfasdf"
    title: "asdfasdf"
}

I added currentlyDisplay: props.posts to react state, props.posts is from global redux state. 我添加了currentlyDisplay: props.posts来反应状态,props.posts来自全局redux状态。 So when you search, it filters out with title value 因此,当您搜索时,它会过滤出标题值

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Modal from 'react-modal';
import _ from 'lodash';
import { getPosts } from '../actions/posts';
import HouseModal from '../components/HouseModal';
import SearchField from '../components/SearchFeild';


export class Houses extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpen: null,
      searchField: '',
      currentlyDisplay: props.posts
    }
  }

  componentDidMount() {
    this.props.getPosts();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.currentlyDisplay !== this.props.currentlyDisplay) {
      this.setState({ currentlyDisplay: nextProps.currentlyDisplay })
    }
  }

  componentWillMount() {
    Modal.setAppElement(document.body);
  }

  onClickHandle = (key) => {
    this.setState({
      ...this.state,
      isOpen: key
    });
  }

  onSearchChange = (event) => {
    let newlyDisplayed = _.filter(this.props.posts, post => post.title.includes(event.target.value))
    this.setState({
      searchField: event.target.value,
      currentlyDisplay: newlyDisplayed
    })
    console.log(this.state.currentlyDisplay)
  }

  currentlyDisplay() {
    return _.map(this.state.currentlyDisplay, (post, key) => {
      <div
        key={key}
        className="card"
        style={{ width: 18 + 'em' }}
        onClick={() => this.onClickHandle(key)}
      >
        <img className="card-img-top" src={post.imageLinks[0]} alt="Card cap" style={{ width: 18 + 'em' }} />
        <div className="card-body">
          <h5 className="card-title">{post.title}</h5>
          <p className="card-text">{post.tag}</p>
        </div>
        <HouseModal
          isOpen={this.state.isOpen === key}
          onClose={this.onClickHandle}
          posts={this.props.posts[key]}
        />
      </div>
    })
  }


  renderPosts() {
    return _.map(this.props.posts, (post, key) => {
      return (
        <div
          key={key}
          className="card"
          style={{ width: 18 + 'em' }}
          onClick={() => this.onClickHandle(key)}
        >
          <img className="card-img-top" src={post.imageLinks[0]} alt="Card cap" style={{ width: 18 + 'em' }} />
          <div className="card-body">
            <h5 className="card-title">{post.title}</h5>
            <p className="card-text">{post.tag}</p>
          </div>
          <HouseModal
            isOpen={this.state.isOpen === key}
            onClose={this.onClickHandle}
            posts={this.props.posts[key]}
          />
        </div>
      );
    });
  }

  render() {
    return (
      <div>
        <SearchField
          searchChange={this.onSearchChange}>
        </SearchField>
        {this.state.searchField ? this.currentlyDisplay() : this.renderPosts()}
      </div>
    )
  }
}


const mapStateToProps = (state) => {
  return {
    posts: state.post,
  }
};

export default connect(mapStateToProps, { getPosts })(Houses);

//search field //搜索字段

const SearchFeild =(props) => {
  return (
    <div className="search-feild__container">
        <input
          type="text"
          className="search-feild"
          onChange={props.searchChange}
          placeholder={"search.."}
        />
      </div>
  )
}

I'm getting this in console from searching but it's not rendering on the page. 我正在通过搜索从控制台获取此信息,但未在页面上呈现。 I'm not sure if this approach is right. 我不确定这种方法是否正确。 I'm so confused of how to handle the global redux state with search function. 我对如何使用搜索功能处理全局redux状态感到困惑。

> (2) [{…}, {…}]
0: {createdAt: 1531563055532, imageLinks: Array(1), tag:
> "asdfasdf", title: "asdf"}
1: {createdAt: 1531563127745, imageLinks:
> Array(3), tag: "asdfasdf", title: "asdfasdf"}

It seems to me that your problem is in the fact that you aren't dispatching the action getPosts, only calling it. 在我看来,您的问题在于您没有调度动作getPosts而是仅对其进行了调用。 That means that the result of that action is not propagated to redux, and your component will not observe the changes. 这意味着该操作的结果不会传播到redux,并且您的组件将不会观察到更改。

Change the mapDispatchToProps object in the connect from: 从以下位置更改连接中的mapDispatchToProps对象:

export default connect(mapStateToProps, { getPosts })(Houses);

to: 至:

const mapDispatchToProps = (dispatch) => ({
    getPosts: () => dispatch(getPosts()) 
})

export default connect(mapStateToProps, mapDispatchToProps)(Houses);

You can then call it anywhere in the component as: 然后可以在组件中的任何位置调用它,如下所示:

const { getPosts } = this.props;
getPosts();

or 要么

this.props.getPosts(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM