1

/keywordsActions

import { UPDATE_KEYWORDS } from "./actionTypes";
import queryString from "query-string";

const keywordsArrayFromUrl = () => {
  const query = queryString.parse(window.location.search);
  if (query.keywords) {
    const removeDuplicate = new Set(query.keywords.split(" "));
    return Array.from(removeDuplicate);
  }

  return [];
};

export function updateKeywords() {
  return async dispatch => {
    dispatch({
      type: UPDATE_KEYWORDS,
      payload: await keywordsArrayFromUrl()
    });
  };
}

/keywordReducer

import { UPDATE_KEYWORDS } from "../actions/actionTypes";

export default function(state = [], action) {
  switch (action.type) {
    case UPDATE_KEYWORDS:
      return action.payload;
    default:
      return state;
  }
}

/SearchBar -- 反应组件

import React, { Component } from "react";
import { withRouter } from "react-router-dom";
//Redux
import { connect } from "react-redux";
import { updateKeywords } from "../store/actions/KeywordsAction";

class Searchbar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keywords : this.props.keywords
      keywordsString: this.props.keywords.join(" ")
    };
  }

  componentDidMount() {
    this.props.updateKeywords();
    console.log(this.props)
    setTimeout(() => console.log(this.props), 10);
  }

  _handleChange = e => {
    this.setState({ keywordsString: e.target.value });
  };

  _handleSearch = value => {
    this.setState({ keywordsString: value });
    this.props.history.push(`/search?keywords=${value}`);
  };

  render() {
    return (
      <Search
        className="Searchbar"
        placeholder="Cauta prin iBac..."
        value={this.state.keywordsString}
        onChange={this._handleChange}
        onSearch={this._handleSearch}
      />
    );
  }
}

const mapStateToProps = state => {
  return {
    keywords: state.keywords
  };
};

export default connect(
  mapStateToProps,
  { updateKeywords }
)(withRouter(Searchbar));

我想将 Url 中的关键字保存到商店,然后将其传递到搜索栏状态。

但我不明白这一点:

  componentDidMount() {
    this.props.updateKeywords();
    console.log(this.props); // this.props.keywords is empty
    setTimeout(() => console.log(this.props), 10); // After 10 ms this.props.keywords is no empty 
  }

10 毫秒后,Searchbar 的 props 会更新,但组件不会再次呈现。

抱歉我的问题,我对 React / Redux 真的很陌生。请让我知道我做错了什么。谢谢你们!

更新 :

  componentDidMount() {
    this.props.updateKeywords();
    setTimeout(() => {
      this.setState({
        keywordsString: this.props.keywords.join(" ")
      });
    }, 0);
  }

这段代码也可以工作......但是另一个不工作

componentDidMount() {
    this.props.updateKeywords();
      this.setState({
        keywordsString: this.props.keywords.join(" ")
      });
  }
4

1 回答 1

0

原因是componentDidMount它只在安装时调用一次。您正在寻找的是componentShouldUpdateor componentDidUpdateor orrender函数,当您的组件从 redux 接收到更新的状态时,所有这些都会被调用。您可以在此处阅读以了解有关这些功能的作用的更多信息。

https://reactjs.org/docs/react-component.html#updating

于 2019-03-27T13:30:46.263 回答