【问题标题】:Binding element 'dispatch' implicitly has an 'any' type. var dispatch: any绑定元素 'dispatch' 隐含地具有 'any' 类型。 var调度:任何
【发布时间】:2018-03-21 02:19:56
【问题描述】:

我遵循这个关于 redux 的示例,但我使用 TypeScript 编写。

https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo

我在AddTodo.tsx 文件中遇到问题。

import * as React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'

const AddTodo = ({ dispatch }) => {
let input: any

return (
  <div>
    <form onSubmit={e => {
      e.preventDefault()
      if (!input.value.trim()) {
        return
      }
      dispatch(addTodo(input.value))
      input.value = ''
    }}>
      <input ref={node => {
        input = node
      }} />
      <button type="submit">
        Add Todo
      </button>
    </form>
  </div>
)
}
AddTodo = connect()(AddTodo)

export default AddTodo

dispatch 参数不允许。错误说:

[ts] 绑定元素 'dispatch' 隐式具有 'any' 类型。

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    也许是类型问题。尝试像这样在你的道具中添加类型:

    import * as React from 'react'
    import { connect } from 'react-redux'
    import { addTodo } from '../actions'
    import { Dispatch } from 'redux';
    
    interface AddTodoProps { 
      dispatch : Dispatch<{}> 
     }
    
    
    const AddTodo = (props : AddTodoProps) => {
    let input: any
    
    return (
      <div>
        <form onSubmit={e => {
          e.preventDefault()
          if (!input.value.trim()) {
            return
          }
          props.dispatch(addTodo(input.value))
          input.value = ''
        }}>
          <input ref={node => {
            input = node
          }} />
          <button type="submit">
            Add Todo
          </button>
        </form>
      </div>
    )
    }
    
    export default connect()(AddTodo)
    

    【讨论】:

    • 你能看看我的回购https://github.com/khuong291/React_ToDo。无法编译。
    • 由于您在tslint.json 文件上编写的 tslint 规则,它无法编译。编译前必须遵守此规则。
    猜你喜欢
    • 2020-06-19
    • 2023-01-28
    • 2023-02-07
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多