You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Redux:POST提交user_resources后前端不实时渲染求助

Hey there, let's dig into why your Profile page isn't updating in real-time after adding a user resource. I've gone through your code and spotted a few potential issues and fixes:

Problem Breakdown

Your Rails backend successfully creates the user_resources record, but the React Native Profile component doesn't reflect the new data until you restart Expo. This is almost always related to how your Redux state is being updated or how your component is reacting to state changes.

Key Issues & Fixes

1. Verify the Redux State Update Flow

Let's start with the most critical part: making sure your Redux store is actually getting the new resource.

Check the addUserResource Action Payload

In your ResourcesScreen component, after the POST request, you log data2 — double-check that this data matches the structure of existing items in user_resources. If the backend returns extra fields or missing required ones (like id), the new item won't render correctly.

Confirm the User Reducer is Updating Correctly

Your ADD_ONE_USER_RESOURCE case in the user reducer looks correct (you're creating a new array instead of mutating the old one), but let's simplify it to eliminate any edge cases:

case "ADD_ONE_USER_RESOURCE":
  return {
    ...state,
    user_resources: [...state.user_resources, action.userResources]
  };

This ensures you're properly immutably updating the state, which Redux requires to detect changes.

2. Make Sure the Profile Component Reacts to Props Changes

Your Profile component uses this.props.users.user_resources to render items, but sometimes nested props can cause issues with React's change detection. Let's adjust how you map state to props to make the resource list explicit:

const mapStateToProps = (state) => {
  return {
    userResources: state.userReducer.user_resources, // Extract resources directly
    users: state.userReducer,
  }
}

Then update the render method to use the direct prop:

render(){
  return(
    <View>
      {this.props.userResources.map(singleResource=> {
        return <Text key={singleResource.id}>{singleResource.name}</Text>
      })}
    </View>
  )
}

This makes it easier for React to detect when the resource list changes, since it's a top-level prop now.

Add a Debug Log to Confirm Updates

Add a componentDidUpdate lifecycle method to your Profile component to verify it's receiving the updated props:

componentDidUpdate(prevProps) {
  if (prevProps.userResources !== this.props.userResources) {
    console.log('New resources added:', this.props.userResources);
  }
}

If you don't see this log when you add a resource, that means the Redux state isn't updating, or the component isn't connected properly.

3. Fix the Delete Method (Unrelated but Critical for Future)

I noticed a typo in your Profile's delete handler — you're calling deleteOneFood but your action is named deleteOneResource. Also, your delete action expects an id, not the whole resource object:

handleDelete = (id) => {
  fetch(`http://localhost:3000/user_resources/${id}`, {
    method: "DELETE",
    headers: { "Authorization": this.props.users.token }
  })
  .then(r => r.json())
  .then(() => {
    this.props.deleteOneResource(id) // Pass the id, not the object
  })
}

And don't forget to add the corresponding case to your user reducer to handle deletion:

case "DELETE_ONE_USER_RESOURCE":
  return {
    ...state,
    user_resources: state.user_resources.filter(resource => resource.id !== action.payload)
  };

4. Check for Navigation Caching

If you're using React Navigation's Tab Navigator, sometimes background tabs are cached and don't re-render immediately. To fix this, you can listen to navigation focus events in your class component:

componentDidMount() {
  this._unsubscribe = this.props.navigation.addListener('focus', () => {
    // Force a re-render when the tab comes into focus
    this.forceUpdate();
  });
}

componentWillUnmount() {
  this._unsubscribe();
}

This ensures the Profile component re-renders every time the user navigates to it, picking up any new resources.

Final Checks
  • Make sure you're using Redux DevTools (if available) to inspect the store after adding a resource — you should see the user_resources array grow with the new item.
  • Confirm that the data2 from your POST request includes an id (since you use it as the key in your map function).

Following these steps should get your Profile page updating in real-time without needing to restart Expo.

内容的提问来源于stack exchange,提问作者st123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:12:52