无状态组件中的表单字段未使用redux-forms和react-native进行初始化
问题描述:
我有一个带有两个字段的基本表单,我希望用某些值进行初始化。即使我将初始值传递给reduxForm,表单中的字段并不会显示最初提供的值。无状态组件中的表单字段未使用redux-forms和react-native进行初始化
谷歌搜索了一下,它仍然不清楚这是否是一种错误形式。
这里是我的组件代码:
const renderInput = ({ input: { onChange, ...restInput}}) => {
return <TextInput onChangeText={onChange} {...restInput} />
}
const RegisterLocationForm = ({handleSubmit}) => {
return (
<View>
<Text>Location Key:</Text>
<Field name="location_key" component={renderInput} />
<Text>Location Secret</Text>
<Field name="location_secret" component={renderInput} />
<Button
onPress={handleSubmit}
title="Register Location"
color="#70c000"
/>
</View>
)
}
RegisterLocationForm.propTypes = {
onSubmit: PropTypes.func.isRequired
}
RegisterLocationForm = reduxForm({
form: 'registerLocation',
initialValues: { location_key: 'A key' , location_secret: 'A secret' }
})(RegisterLocationForm)
export default RegisterLocationForm
In this post他们建议使用组件的生命周期进行初始化,但我使用的是无状态的组件,所以我不能使用回调像componentDidMount。
有没有人遇到过类似的问题?我究竟做错了什么?
编辑
我发现它的实际工作。但是,我在做TDD,测试是失败的。这是测试失败:
const middlewares = []
const mockStore = configureStore(middlewares)
test('renders correctly',() => {
tree = renderer.create(
<Provider store={store}>
<RegisterLocationForm onSubmit={() => {} } initialValues={{
location_key: '12345678-1234-1234-1234-123456789012',
location_secret: '12345678-1234-1234-1234-123456789012'
}} />
</Provider>
).toJSON()
expect(tree).toMatchSnapshot()
})
我手动设置快照的期望值。测试失败,因为该字段的值仍为空。
它不应该与初始值进行更新?
答
通常我以这种方式为我的redux-form(in react)创建JEST快照测试。这种格式适用于我的大部分还原形式。
对于无状态的部件,除去initialStateValues并用替换存储: 常量存储= createStore(()=>({}))
import React from 'react'
import renderer from 'react-test-renderer'
import RegisterLocationForm from '../RegisterLocationForm/RegisterLocationForm' //Import your redux
form component
import { reduxForm } from 'redux-form'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
jest.mock('react-dom')
const spy = jest.fn()
const initialStateValues = {
//Pass your initialStateValues of your redux-form component
}
const store = createStore((state) => state, initialStateValues)
const Decorated = reduxForm({
form: 'testForm', onSubmit: { spy }
})(RegisterLocationForm)
const defaultFormValues = {
//You can pass form initialValues here
}
it('RegisterLocationForm renders correctly',() => {
const tree = renderer.create(
<Provider store={store}>
<Decorated
{...defaultFormValues}
/>
</Provider>
).toJSON()
expect(tree).toMatchSnapshot()
})