React Router / Context API搜索组件

时间:2019-05-07 13:37:08

标签: reactjs react-router

我曾经使该代码适合我的搜索组件,但是在调用on Submit之后,我收到了从未发生过的错误,有人有任何线索吗?

已超过最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。

import React, { Component } from "react";
import axios from "axios";
import { Redirect } from "react-router-dom";
import { Consumer } from "../context";
class Search extends Component {
  constructor() {
    super();
    this.state = {
      productTitle: "",
      apiUrl: "*******************************",
      redirect: false
    };
  }

  findProduct = (dispatch, e) => {
    e.preventDefault();

    axios
      .post(
        `${this.state.apiUrl}`,
        JSON.stringify({ query: this.state.productTitle })
      )
      .then(res => {
        dispatch({
          type: "SEARCH_TRACKS",
          payload: res.data.output.items
        });

        this.setState({ items: res.data.output.items, redirect: true });
      })
      .catch(err => console.log(err));
  };
  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };
  render() {
    const { redirect } = this.state;

    if (redirect) {
      return <Redirect to="/searchresult" />;
    }
    return (
      <Consumer>
        {value => {
          const { dispatch } = value;
          return (
            <div>
              <form onSubmit={this.findProduct.bind(this, dispatch)}>
                <div className="form-group" id="form_div">
                  <input
                    type="text"
                    className="form-control form-control-md"
                    placeholder="...محصولات دسته یا برند مورد نظرتان را انتخاب کنید"
                    name="productTitle"
                    value={this.state.productTitle}
                    onChange={this.onChange}
                  />

                  <button className="btn" type="submit">
                    <i className="fas fa-search" />
                  </button>
                </div>
              </form>
            </div>
          );
        }}
      </Consumer>
    );
  }
}

import React, { Component } from 'react'
import axios from 'axios'
const Context = React.createContext();


export const axiosDashboard = () => {
  const URL = (`*****************`);
  return axios(URL, {
    method: 'POST',
    data: JSON.stringify({refresh:"true"}),
  })
    .then(response => response.data)
    .catch(error => {
      throw error;
    });  
};

const reducer = (state, action) => {
   switch(action.type){
     case 'SEARCH_TRACKS':
       return {
         ...state,
         items: action.payload,
         heading: 'Search Results'
       };
   default:
     return state;
   }
}

export class Provider extends Component {
  state = { 
    dispatch:action => this.setState(state => reducer(state, action))
  }
  render() {
    return (
      <Context.Provider value={this.state}>
         {this.props.children}
      </Context.Provider>
    )
  }
}
export const Consumer = Context.Consumer
import React, { Component } from 'react'
import { Consumer } from '../context'
import SearchResult from './SearchResult'
import './Search.css'

class Tracks extends Component {
  render() {
    return (
      <Consumer>
        {value => {
           const { items } = value
             if(items === undefined || items.length === 0){
               return 'hello'}
             else{
               return(
                 <React.Fragment>
                   <div id='products_search'>
                     <div className='container'>
                       <div className="row justify-content-end">
                         {items.map(item => ( 
                           <SearchResult 
                             key={item.id} 
                             id={item.id} 
                             title={item.name} 
                             current_price={item.current_price} 
                             lowest_price={item.lowest_price} 
                             store_name={item.store_name} 
                             thumb={item.thumb_url}/>        
                          ))}
                       </div>
                     </div>
                   </div>
                 </React.Fragment> 
                )
              }
          }}
      </Consumer>
    )
  }
}
export default Tracks

import React from 'react'
import {Link} from 'react-router-dom'
import './Search.css'
const SearchResult = (props) => {
const {title,current_price,lowest_price,thumb,id,store_name} = props
return (
    <div className="col-md-3" id="searchresult">
        <img src={thumb} alt=""/>
        <div className="sexy_line"></div>
        <p className="muted">{store_name}</p>
        <h6>{title}</h6>
        <p>{lowest_price}</p>
        <Link to={`products/item/${id}`}>
          <button type="button" className="btn btn-light rounded-pill">{
                    new Intl
                        .NumberFormat({style: 'currency', currency: 'IRR'})
                        .format(current_price)
                }</button>
        </Link>
    </div>
  )
}
export default SearchResult

1 个答案:

答案 0 :(得分:0)

  

已超过最大更新深度。

这意味着您处于重新渲染组件的无限循环中。

我可以看到的唯一可能发生的地方是这部分

if (redirect) {
    return <Redirect to="/searchresult" />;
}

也许您正在重新路由到将获得具有重定向的相同组件的路由。

请检查您是否未重定向到与此组件相同的路由,并提供您的路由以及Consumer中的内容。