React上下文API和useState挂钩中的React Native更新状态

时间:2020-05-07 11:53:19

标签: reactjs react-native react-hooks

我有一个带有表单的组件,提交后我想清除表单值。但是它不清楚在何处清空表单值。因为我必须传递回调或上下文中的某些东西来在组件中设置Form值。

我的带有表单的组件

const { updateUserData, state} = useContext(UserContext);

const [name, setName] = useState(state.name);
const [age, setAge] = useState(state.age);

<Input
  value={name}
  label='Enter Name'
  placeholder=''
  onChangeText={(value) => setName(value)}
/>
<Input
  value={age}
  label='Enter Age'
  placeholder=''
  onChangeText={(value) => setAge(value)}
/>

<Button
  onPress={() => {
    let formData = { name, age }
    updateUserData(formData)
  }}>
Update Data
</Button>

我的上下文和Reducer在单独的文件中

const updateUserData= (dispatch) => async (formData) => {
  // Validation functions
  // If validation fails the name and age values cannot be changed
  if(!valid){
    dispatch({ type: 'NOT_VALID', payload: // errors to be shown })
  }

  // Some API functions
  dispatch({ type: 'RESET_FORM' })
}

const userReduucer= (state, action) => {
  switch (action.type) {
    case 'RESET_FORM':
      return {
        ...state,
        name: '',
        age: '',
      };
  }
}

export const { Context, Provider } = createDataContext(
    userReduucer,
    { updateUserData },
    { name: '', age: '' },
)

1 个答案:

答案 0 :(得分:2)

名称和年龄值正在本地更改,因此您也需要在本地重置状态,而不仅仅是在redux存储中

public Classroom(String studID, String subjectID, String dateEnroled)
{  
    this.studID = studID; 
    this.courseID = subjectID;
    this.dateEnroled = new java.text.SimpleDateFormat("yyyy-MM-dd")
                       .parse(dateEnroled);
}

但是,由于您对updateUserData中的值运行验证,因此您可以编写useEffect将局部值更新为reducer的值

<Button
  onPress={() => {
    let formData = { name, age }
    updateUserData(formData);
    setName('');
    setAge('');
  }}>