无法从搜索功能获取正确的数据

时间:2018-07-23 20:14:04

标签: javascript reactjs redux react-redux

当我在组件状态下编写搜索功能时,得到了预期的结果。例如,我查询了Google图书api,并搜索了Halo。我得到了我所期望的效果,例如《光晕:伸手可及的距离》,《光晕:洪水》 ...等。

但是当我将搜索功能移至Redux时,无论我进行什么搜索,我都会得到相同的错误数据。这是怎么发生的?

这是我在redux中的动作

export const searchedBooks = search => async dispatch => {
  const url = `https://www.googleapis.com/books/v1/volumes?q=${search}&orderBy=relevance&maxResults=30&key=API_KEY`;

  try {
    const res = await axios.get(url, {
      transformRequest: [
        (data, headers) => {
          delete headers["access-token"];
          delete headers["uid"];
          delete headers["client"];
          delete headers["expiry"];
          delete headers["token-type"];
          delete headers.common;
          return data;
        }
      ]
    });
    dispatch({
      type: SEARCH_BOOKS,
      payload: res.data
    });
  } catch (error) {
    dispatch({
      type: GET_ERRORS,
      payload: error.response.data
    });
  }
};

在将其付诸行动之前,我先在React中对其进行了测试。它与我使用的代码几乎相同。我相信该错误来自$ {search},我不知道模板文字在Redux中是否能正常工作。

我进行搜索的组件

class Search extends Component {
  state = {
    search: "",
    books: []
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }
  }

  searchBooks = e => {
    e.preventDefault();
    this.props.searchedBooks();
  };

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  render() {
    console.log(this.props.books);
    return (
      <div>
        <h1>hi from search</h1>
        <form>
          <input
            onChange={this.onChange}
            type="text"
            name="search"
            placeholder="Title or Author(s)"
            value={this.state.search}
          />
          <button onClick={this.searchBooks}>Search</button>
        </form>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  books: state.books
});
export default connect(
  mapStateToProps,
  { searchedBooks }
)(Search);

1 个答案:

答案 0 :(得分:2)

您实际上并没有将参数传递给this.props.searchedBooks。大概您想从输入中获取值,因此只需将searchBooks更新为:

searchBooks = e => {
    e.preventDefault();
    this.props.searchedBooks(this.state.search);
};