Jonathan Star 2023-05-31 16:04 采纳率: 70.5%
浏览 20
已结题

react 页面跳转怎么写呀

react 页面跳转怎么写呀

import React from 'react';
import { AutoComplete, Input } from 'antd';
import axios from 'axios';
// import { useHistory } from 'react-router-dom';
// import { useHistory } from 'react-router-dom'
import { useNavigate } from 'react-router-dom';
// import { withRouter } from 'react-router-dom';

interface AutoCompleteSearchBoxProps {
  history: any; // 这里的类型可以根据你的实际需求进行调整
}

interface AutoCompleteSearchBoxState {
  searchResults: any[]; // 假设搜索结果是一个对象数组,每个对象包含label属性
}
// AutoCompleteSearchBox.tsx
class AutoCompleteSearchBox extends React.Component {
  // const history = useHistory();

  // ···
  //     const history = useHistory()
  //     history.push('/xxx')

  constructor(props: AutoCompleteSearchBoxProps) {
    super(props);
    // this.state = {
    //   searchResults: []
    // };
  }


  state = {
    searchResults: [],
    inputRef:{}
  };

  handleSearch = (value:any) => {
    if (value) {
      // 发送远程搜索请求
      axios.get(`https://api.example.com/search?q=${value}`)
        .then((response) => {
          const searchResults = response.data.results;
          this.setState({ searchResults });
        })
        .catch((error) => {
          console.error('Error fetching search results:', error);
          let response={
            data:{
              results:[
                {  
                  label: "dadad"
                },
                {
                  label: "ada"
                }
               ]
            }
          }
          const searchResults = response.data.results;
          this.setState({ searchResults });
        });
    } else {
      this.setState({ searchResults: [] });
    }
  };

  handleSelect = (value:any) => {
    // 将选择的关键词填充到输入框中
    // this.inputRef.input.input.value = value;
    // this.state.inputRef.input.input.value = value;
    this.state.inputRef.input.value = value;
    const navigate = useNavigate();
    const path = `/details/${value}`;
    navigate(path);
    console.log("this.props");
    console.log(this.props);

    // this.props.history.push(path);
    // antd ts react 界面跳转

  };

  render() {
    const { searchResults } = this.state;

    return (
      <div>
        <AutoComplete
          style={{ width: 200 }}
          options={searchResults.map((result) => ({
            value: result.label,
            label: result.label,
          }))}
          onSearch={this.handleSearch}
          onSelect={this.handleSelect}
        >
          <Input
          //  this.inputRef = ref; 
            ref={(ref) => { this.state.inputRef = ref; }}
            placeholder="请输入关键字"
          />
        </AutoComplete>
      </div>
    );
  }
}

export default AutoCompleteSearchBox;


报错


pment.js:16227  Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at Object.throwInvalidHookError (react-dom.development.js:16227:9)
    at Object.useContext (react.development.js:1618:21)
    at useNavigate (hooks.tsx:177:31)
    at handleSelect (AutoCompleteSearchBox.tsx:72:22)
    at triggerSelect2 (Select.js:356:7)
    at Object.current (Select.js:380:5)
    at useRefFunc.js:11:28
    at onSelectValue2 (OptionList.js:150:7)
    at onClick (OptionList.js:329:11)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
throwInvalidHookError @ react-dom.development.js:16227
useContext @ react.development.js:1618
useNavigate @ hooks.tsx:177
handleSelect @ AutoCompleteSearchBox.tsx:72
triggerSelect2 @ Select.js:356
(匿名) @ Select.js:380
(匿名) @ useRefFunc.js:11
onSelectValue2 @ OptionList.js:150
onClick @ OptionList.js:329
callCallback2 @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(匿名) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Test:1  Unchecked runtime.lastError: The message port closed before a response was received.
  • 写回答

2条回答 默认 最新

  • Jonathan Star 2023-05-31 16:16
    关注
       "react-router-dom": "^6.3.0",
    

    这个版本只能函数
    react-router-dom使用指南(最新V6.0.1) - 知乎
    https://zhuanlan.zhihu.com/p/431389907

    import React, { useState, useRef } from 'react';
    import { AutoComplete, Input } from 'antd';
    import axios from 'axios';
    import { useNavigate } from 'react-router-dom';
    
    interface AutoCompleteSearchBoxProps {
      history: any; // 这里的类型可以根据你的实际需求进行调整
    }
    
    interface SearchResult {
      label: string;
    }
    
    const AutoCompleteSearchBox: React.FC<AutoCompleteSearchBoxProps> = (props) => {
      const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
      const inputRef = useRef<Input>(null);
      const navigate = useNavigate();
    
      const handleSearch = (value: string) => {
        if (value) {
          // 发送远程搜索请求
          axios
            .get(`https://api.example.com/search?q=${value}`)
            .then((response) => {
              const searchResults = response.data.results;
              setSearchResults(searchResults);
            })
            .catch((error) => {
              console.error('Error fetching search results:', error);
              const searchResults: SearchResult[] = [
                {
                  label: "dadad"
                },
                {
                  label: "ada"
                }
              ];
              setSearchResults(searchResults);
            });
        } else {
          setSearchResults([]);
        }
      };
    
      const handleSelect = (value: string) => {
        console.log("inputRef.current");
        console.log(inputRef.current);
        inputRef.current?.focus();
        // console.log(    "inputRef.current?.input.setValue");
        // console.log(    inputRef.current?.input.setValue);
    
        // inputRef.current?.input.setValue(value);
    
        let  inputItem= inputRef.current?.input
        inputItem.value=value
        const path = `/details/${value}`;
        navigate(path);
        console.log("props");
        console.log(props);
    
        console.log("props.history");
        console.log(props.history);
      };
    
      return (
        <div>
          <AutoComplete
            style={{ width: 200 }}
            options={searchResults.map((result) => ({
              value: result.label,
              label: result.label,
            }))}
            onSearch={handleSearch}
            onSelect={handleSelect}
          >
            <Input
              ref={inputRef}
              placeholder="请输入关键字"
            />
          </AutoComplete>
        </div>
      );
    };
    
    export default AutoCompleteSearchBox;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月18日
  • 已采纳回答 6月10日
  • 创建了问题 5月31日

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失