Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用typescript响应上下文_Reactjs_Typescript_React Context - Fatal编程技术网

Reactjs 使用typescript响应上下文

Reactjs 使用typescript响应上下文,reactjs,typescript,react-context,Reactjs,Typescript,React Context,我想在React-Typescript项目中使用上下文,如何才能做到这一点 我有以下代码: App.js 现在,问题是value和setValue都有相同的错误消息: 类型“ValueContextType |未定义”上不存在属性“setValue” 我如何才能做到这一点?我找到了一个可行的解决方案: App.js import {Context} from 'context' const App = () => { type ValueContextType = { value

我想在React-Typescript项目中使用上下文,如何才能做到这一点

我有以下代码: App.js

现在,问题是value和setValue都有相同的错误消息:

类型“ValueContextType |未定义”上不存在属性“setValue”


我如何才能做到这一点?

我找到了一个可行的解决方案:

App.js

import {Context} from 'context'

const App = () => {
  type ValueContextType = {
  value: string;
  setValue: (value: string) => void;
  }
  const [value, setValue] = useState<ValueContextType | any>("");
  return (
    <Router>
       <Context.Provider value={{value, setValue}}>
       ... some routes
       </Context.Provider>
    </Router>
  )
}

我不知道这是不是“hacky”,但它可以工作。

您在哪里定义
setTitle
?对不起,输入错误!这是设定值。现在已更新。如果没有对您的解决方案的任何概述,这可能是过火了;是否应该使用Redux存储共享此解决方案?无法共享整个解决方案,因为它包含100个文件。我还不习惯redux,所以现在上下文效果更好。但是我发布了一个有效的答案。
const[value,setValue]=useContext(ValueContext)
import {createContext} from 'react';

type ValueContextType = {
  value: string;
  setValue: (value: string) => void;
}

export const ValueContext = createContext<ValueContextType | undefined>(undefined);
import {ValueContext} from 'context'

const Users () => {
  const {value, setValue} = useContext(ValueContext);
}
import {Context} from 'context'

const App = () => {
  type ValueContextType = {
  value: string;
  setValue: (value: string) => void;
  }
  const [value, setValue] = useState<ValueContextType | any>("");
  return (
    <Router>
       <Context.Provider value={{value, setValue}}>
       ... some routes
       </Context.Provider>
    </Router>
  )
}
import {createContext} from 'react';

type ValueContextType = {
  value: string;
  setValue: (value: string) => void;
}

export const ValueContext = createContext<ValueContextType | any>("");
import {ValueContext} from 'context'

const Users () => {
  const {value, setValue} = useContext(ValueContext);
}