Locastro's line drive to left field scored Nick Ahmed and helped the Diamondbacks end a season-long six-game losing streak.
Matt Andriese (4-4) pitched a scoreless top of the 10th to earn the win. Christian Walker had three hits for Arizona.
Kevin Pillar homered for the Giants, his 10th of the season, but San Francisco was held to four hits for the game.
Locastro rolled a single into shallow right field, the Diamondbacks' first hit of the game, driving in Caleb Joseph with two outs in the third inning. The Giants tied the score at 1 on Stephen Vogt's ground out to score Evan Longoria from third base in the top of the fourth.
Arizona went back in front 2-1 with Walker's RBI single in the fourth, the result of a nine-pitch at-bat that drove in Adam Jones, who'd reached on a wild pitch third strike.
Pillar led off the seventh inning with a solo shot to left field, which spelled the end of Diamondbacks starter Merrill Kelly's day. Kelly went six innings and allowed two runs on four hits, striking out nine.
The Diamondbacks opened their half of the seventh with back-to-back hits off Giants starter Shaun Anderson to put runners on second and third, and the Giants turned to Reyes Moronta in relief. Moronta worked out of the jam without allowing a hit.
Anderson allowed two runs on five hits in six innings.
WILD PITCH, WILD OUT
The Diamondbacks were primed to take the lead in the seventh with Ahmed up to bat and runners in scoring position with no outs. Moronta threw a pitch to the backstop, but the carom arrived cleanly to catcher Vogt's glove, and Vogt had plenty of time to tag out Eduardo Escobar trying to score from third base.
The Diamondbacks failed to score in the inning.
Giants: Vogt took a foul ball of his right knee in the bottom of the fifth inning and was limping badly for a few moments immediately afterward, but remained in the game.
Diamondbacks: 2B-OF Ketel Marte was held out of the lineup for a second straight day due to a minor groin injury from Friday's game.
Giants: LHP Drew Pomeranz (2-7, 7.09 ERA) is set to face the Colorado Rockies in the opener of a three-game series that starts Monday in San Francisco.
Diamondbacks: RHP Zack Greinke (8-3, 2.91) is tabbed for the opener of a three-game series against the Los Angeles Dodgers starting Monday. He could face the Dodgers' Clayton Kershaw, a former teammate and fellow Cy Young Award winner, for the second time in his career.
More AP MLB: https://apnews.com/MLB and https://twitter.com/AP-Sports