【发布时间】:2017-12-10 12:34:23
【问题描述】:
我无法理解为什么在提供渲染功能时不进行渲染,而不是直接返回 JSX。
这是我的 InputBox 组件示例:
export default React => {
const InputBox = ({ city, setCity, setTime }) => {
const onInputEnter = createOnInputEnter({ city, setCity, setTime, getCityTime })
return (
<div className='InputBox'>
<input
defaultValue={city}
onKeyPress={onInputEnter}
onFocus={moveFocusAtEnd}
autoFocus />
</div>
)
}
return InputBox
}
在这种情况下,每次我更改城市的 redux 状态时都会重新渲染城市。
export default React => {
const InputBox = ({ city, setCity, setTime }) => {
const onInputEnter = createOnInputEnter({ city, setCity, setTime, getCityTime })
const componentDidMount = async () => {
const { city: resultCity, time: resultTime } = await getCityTime(city)
setCity(resultCity)
setTime(resultTime)
}
const render = () => {
return (
<div className='InputBox'>
<input
defaultValue={city}
onKeyPress={onInputEnter}
onFocus={moveFocusAtEnd}
autoFocus />
</div>
)
}
return { render, componentDidMount }
}
return InputBox
}
在这个例子中,城市只被传递一次,当 redux 状态改变时不会重新渲染。
我想使用后一个示例,因为我使用 componentDidMount 方法进行初始化。
我在这个例子中使用了 React 和 React-Redux。
这就是我的 InputBox 容器的样子:
import createInputBox from '../components/InputBox.js'
import { connect } from 'react-redux'
...
export default React => {
const InputBox = createInputBox(React)
const InputBoxWithReduxStore = connect(
({ city }) => ({ city }),
mapDispatchToProps
)(InputBox)
return InputBoxWithReduxStore
}
编辑:
我包含代码 sn-p 以显示 createOnInputEnter 函数的实现
function createOnInputEnter ({ city, setCity, setTime, getCityTime }) {
return async ({ key, target }) => {
if (key === 'Enter') {
try {
const inputCity = target.value
setTime('...')
const { city: resultCity, time: resultTime } = await getCityTime(inputCity)
setCity(resultCity)
setTime(resultTime)
} catch (err) {
const { city: resultCity, time: resultTime } = await getCityTime(city)
setCity(resultCity)
setTime(resultTime)
}
}
}
}
正如@zarcode 建议使用 React.Component,它不符合我的要求。因为我使用无类组件。更多关于 Mixin 部分:https://gist.github.com/jquense/47bbd2613e0b03d7e51c
【问题讨论】:
-
@RIYAJKHAN codesandbox.io/s/8kvozyw682
-
@PeterParada,哪里没有发生渲染
-
@ShubhamKhatri 关于 createOnInputEnter 函数的 catch 子句 - city 仍然是默认的,即使您在 redux 状态下更改它。
标签: javascript reactjs redux react-redux